core/iter/traits/iterator.rs
1use super::super::{
2 ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, FlatMap,
3 Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, MapWindows, Peekable,
4 Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, TrustedRandomAccessNoCoerce,
5 Zip, try_process,
6};
7use super::TrustedLen;
8use crate::array;
9use crate::cmp::{self, Ordering};
10use crate::num::NonZero;
11use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
12
13fn _assert_is_dyn_compatible(_: &dyn Iterator<Item = ()>) {}
14
15/// A trait for dealing with iterators.
16///
17/// This is the main iterator trait. For more about the concept of iterators
18/// generally, please see the [module-level documentation]. In particular, you
19/// may want to know how to [implement `Iterator`][impl].
20///
21/// [module-level documentation]: crate::iter
22/// [impl]: crate::iter#implementing-iterator
23#[stable(feature = "rust1", since = "1.0.0")]
24#[rustc_on_unimplemented(
25 on(
26 Self = "core::ops::range::RangeTo<Idx>",
27 note = "you might have meant to use a bounded `Range`"
28 ),
29 on(
30 Self = "core::ops::range::RangeToInclusive<Idx>",
31 note = "you might have meant to use a bounded `RangeInclusive`"
32 ),
33 label = "`{Self}` is not an iterator",
34 message = "`{Self}` is not an iterator"
35)]
36#[doc(notable_trait)]
37#[lang = "iterator"]
38#[rustc_diagnostic_item = "Iterator"]
39#[must_use = "iterators are lazy and do nothing unless consumed"]
40#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
41pub const trait Iterator {
42 /// The type of the elements being iterated over.
43 #[rustc_diagnostic_item = "IteratorItem"]
44 #[stable(feature = "rust1", since = "1.0.0")]
45 type Item;
46
47 /// Advances the iterator and returns the next value.
48 ///
49 /// Returns [`None`] when iteration is finished. Individual iterator
50 /// implementations may choose to resume iteration, and so calling `next()`
51 /// again may or may not eventually start returning [`Some(Item)`] again at some
52 /// point.
53 ///
54 /// [`Some(Item)`]: Some
55 ///
56 /// # Examples
57 ///
58 /// ```
59 /// let a = [1, 2, 3];
60 ///
61 /// let mut iter = a.into_iter();
62 ///
63 /// // A call to next() returns the next value...
64 /// assert_eq!(Some(1), iter.next());
65 /// assert_eq!(Some(2), iter.next());
66 /// assert_eq!(Some(3), iter.next());
67 ///
68 /// // ... and then None once it's over.
69 /// assert_eq!(None, iter.next());
70 ///
71 /// // More calls may or may not return `None`. Here, they always will.
72 /// assert_eq!(None, iter.next());
73 /// assert_eq!(None, iter.next());
74 /// ```
75 #[lang = "next"]
76 #[stable(feature = "rust1", since = "1.0.0")]
77 fn next(&mut self) -> Option<Self::Item>;
78
79 /// Advances the iterator and returns an array containing the next `N` values.
80 ///
81 /// If there are not enough elements to fill the array then `Err` is returned
82 /// containing an iterator over the remaining elements.
83 ///
84 /// # Examples
85 ///
86 /// Basic usage:
87 ///
88 /// ```
89 /// #![feature(iter_next_chunk)]
90 ///
91 /// let mut iter = "lorem".chars();
92 ///
93 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
94 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
95 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
96 /// ```
97 ///
98 /// Split a string and get the first three items.
99 ///
100 /// ```
101 /// #![feature(iter_next_chunk)]
102 ///
103 /// let quote = "not all those who wander are lost";
104 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
105 /// assert_eq!(first, "not");
106 /// assert_eq!(second, "all");
107 /// assert_eq!(third, "those");
108 /// ```
109 #[inline]
110 #[unstable(feature = "iter_next_chunk", issue = "98326")]
111 #[rustc_non_const_trait_method]
112 fn next_chunk<const N: usize>(
113 &mut self,
114 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
115 where
116 Self: Sized,
117 {
118 array::iter_next_chunk(self)
119 }
120
121 /// Returns the bounds on the remaining length of the iterator.
122 ///
123 /// Specifically, `size_hint()` returns a tuple where the first element
124 /// is the lower bound, and the second element is the upper bound.
125 ///
126 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
127 /// A [`None`] here means that either there is no known upper bound, or the
128 /// upper bound is larger than [`usize`].
129 ///
130 /// # Implementation notes
131 ///
132 /// It is not enforced that an iterator implementation yields the declared
133 /// number of elements. A buggy iterator may yield less than the lower bound
134 /// or more than the upper bound of elements.
135 ///
136 /// `size_hint()` is primarily intended to be used for optimizations such as
137 /// reserving space for the elements of the iterator, but must not be
138 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
139 /// implementation of `size_hint()` should not lead to memory safety
140 /// violations.
141 ///
142 /// That said, the implementation should provide a correct estimation,
143 /// because otherwise it would be a violation of the trait's protocol.
144 ///
145 /// The default implementation returns <code>(0, [None])</code> which is correct for any
146 /// iterator.
147 ///
148 /// # Examples
149 ///
150 /// Basic usage:
151 ///
152 /// ```
153 /// let a = [1, 2, 3];
154 /// let mut iter = a.iter();
155 ///
156 /// assert_eq!((3, Some(3)), iter.size_hint());
157 /// let _ = iter.next();
158 /// assert_eq!((2, Some(2)), iter.size_hint());
159 /// ```
160 ///
161 /// A more complex example:
162 ///
163 /// ```
164 /// // The even numbers in the range of zero to nine.
165 /// let iter = (0..10).filter(|x| x % 2 == 0);
166 ///
167 /// // We might iterate from zero to ten times. Knowing that it's five
168 /// // exactly wouldn't be possible without executing filter().
169 /// assert_eq!((0, Some(10)), iter.size_hint());
170 ///
171 /// // Let's add five more numbers with chain()
172 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
173 ///
174 /// // now both bounds are increased by five
175 /// assert_eq!((5, Some(15)), iter.size_hint());
176 /// ```
177 ///
178 /// Returning `None` for an upper bound:
179 ///
180 /// ```
181 /// // an infinite iterator has no upper bound
182 /// // and the maximum possible lower bound
183 /// let iter = 0..;
184 ///
185 /// assert_eq!((usize::MAX, None), iter.size_hint());
186 /// ```
187 #[inline]
188 #[stable(feature = "rust1", since = "1.0.0")]
189 fn size_hint(&self) -> (usize, Option<usize>) {
190 (0, None)
191 }
192
193 /// Consumes the iterator, counting the number of iterations and returning it.
194 ///
195 /// This method will call [`next`] repeatedly until [`None`] is encountered,
196 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
197 /// called at least once even if the iterator does not have any elements.
198 ///
199 /// [`next`]: Iterator::next
200 ///
201 /// # Overflow Behavior
202 ///
203 /// The method does no guarding against overflows, so counting elements of
204 /// an iterator with more than [`usize::MAX`] elements either produces the
205 /// wrong result or panics. If overflow checks are enabled, a panic is
206 /// guaranteed.
207 ///
208 /// # Panics
209 ///
210 /// This function might panic if the iterator has more than [`usize::MAX`]
211 /// elements.
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// let a = [1, 2, 3];
217 /// assert_eq!(a.iter().count(), 3);
218 ///
219 /// let a = [1, 2, 3, 4, 5];
220 /// assert_eq!(a.iter().count(), 5);
221 /// ```
222 #[inline]
223 #[stable(feature = "rust1", since = "1.0.0")]
224 #[rustc_non_const_trait_method]
225 fn count(self) -> usize
226 where
227 Self: Sized,
228 {
229 self.fold(
230 0,
231 #[rustc_inherit_overflow_checks]
232 |count, _| count + 1,
233 )
234 }
235
236 /// Consumes the iterator, returning the last element.
237 ///
238 /// This method will evaluate the iterator until it returns [`None`]. While
239 /// doing so, it keeps track of the current element. After [`None`] is
240 /// returned, `last()` will then return the last element it saw.
241 ///
242 /// # Panics
243 ///
244 /// This function might panic if the iterator is infinite.
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// let a = [1, 2, 3];
250 /// assert_eq!(a.into_iter().last(), Some(3));
251 ///
252 /// let a = [1, 2, 3, 4, 5];
253 /// assert_eq!(a.into_iter().last(), Some(5));
254 /// ```
255 #[inline]
256 #[stable(feature = "rust1", since = "1.0.0")]
257 #[rustc_non_const_trait_method]
258 fn last(self) -> Option<Self::Item>
259 where
260 Self: Sized,
261 {
262 #[inline]
263 fn some<T>(_: Option<T>, x: T) -> Option<T> {
264 Some(x)
265 }
266
267 self.fold(None, some)
268 }
269
270 /// Advances the iterator by `n` elements.
271 ///
272 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
273 /// times until [`None`] is encountered.
274 ///
275 /// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by
276 /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,
277 /// where `k` is remaining number of steps that could not be advanced because the iterator ran out.
278 /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
279 /// Otherwise, `k` is always less than `n`.
280 ///
281 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
282 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
283 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
284 ///
285 /// [`Flatten`]: crate::iter::Flatten
286 /// [`next`]: Iterator::next
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// #![feature(iter_advance_by)]
292 ///
293 /// use std::num::NonZero;
294 ///
295 /// let a = [1, 2, 3, 4];
296 /// let mut iter = a.into_iter();
297 ///
298 /// assert_eq!(iter.advance_by(2), Ok(()));
299 /// assert_eq!(iter.next(), Some(3));
300 /// assert_eq!(iter.advance_by(0), Ok(()));
301 /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped
302 /// ```
303 #[inline]
304 #[unstable(feature = "iter_advance_by", issue = "77404")]
305 #[rustc_non_const_trait_method]
306 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
307 /// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators.
308 trait SpecAdvanceBy {
309 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
310 }
311
312 impl<I: Iterator + ?Sized> SpecAdvanceBy for I {
313 default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
314 for i in 0..n {
315 if self.next().is_none() {
316 // SAFETY: `i` is always less than `n`.
317 return Err(unsafe { NonZero::new_unchecked(n - i) });
318 }
319 }
320 Ok(())
321 }
322 }
323
324 impl<I: Iterator> SpecAdvanceBy for I {
325 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
326 let Some(n) = NonZero::new(n) else {
327 return Ok(());
328 };
329
330 let res = self.try_fold(n, |n, _| NonZero::new(n.get() - 1));
331
332 match res {
333 None => Ok(()),
334 Some(n) => Err(n),
335 }
336 }
337 }
338
339 self.spec_advance_by(n)
340 }
341
342 /// Returns the `n`th element of the iterator.
343 ///
344 /// Like most indexing operations, the count starts from zero, so `nth(0)`
345 /// returns the first value, `nth(1)` the second, and so on.
346 ///
347 /// Note that all preceding elements, as well as the returned element, will be
348 /// consumed from the iterator. That means that the preceding elements will be
349 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
350 /// will return different elements.
351 ///
352 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
353 /// iterator.
354 ///
355 /// # Examples
356 ///
357 /// Basic usage:
358 ///
359 /// ```
360 /// let a = [1, 2, 3];
361 /// assert_eq!(a.into_iter().nth(1), Some(2));
362 /// ```
363 ///
364 /// Calling `nth()` multiple times doesn't rewind the iterator:
365 ///
366 /// ```
367 /// let a = [1, 2, 3];
368 ///
369 /// let mut iter = a.into_iter();
370 ///
371 /// assert_eq!(iter.nth(1), Some(2));
372 /// assert_eq!(iter.nth(1), None);
373 /// ```
374 ///
375 /// Returning `None` if there are less than `n + 1` elements:
376 ///
377 /// ```
378 /// let a = [1, 2, 3];
379 /// assert_eq!(a.into_iter().nth(10), None);
380 /// ```
381 #[inline]
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[rustc_non_const_trait_method]
384 fn nth(&mut self, n: usize) -> Option<Self::Item> {
385 self.advance_by(n).ok()?;
386 self.next()
387 }
388
389 /// Creates an iterator starting at the same point, but stepping by
390 /// the given amount at each iteration.
391 ///
392 /// Note 1: The first element of the iterator will always be returned,
393 /// regardless of the step given.
394 ///
395 /// Note 2: The time at which ignored elements are pulled is not fixed.
396 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
397 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
398 /// `advance_n_and_return_first(&mut self, step)`,
399 /// `advance_n_and_return_first(&mut self, step)`, …
400 /// Which way is used may change for some iterators for performance reasons.
401 /// The second way will advance the iterator earlier and may consume more items.
402 ///
403 /// `advance_n_and_return_first` is the equivalent of:
404 /// ```
405 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
406 /// where
407 /// I: Iterator,
408 /// {
409 /// let next = iter.next();
410 /// if n > 1 {
411 /// iter.nth(n - 2);
412 /// }
413 /// next
414 /// }
415 /// ```
416 ///
417 /// # Panics
418 ///
419 /// The method will panic if the given step is `0`.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// let a = [0, 1, 2, 3, 4, 5];
425 /// let mut iter = a.into_iter().step_by(2);
426 ///
427 /// assert_eq!(iter.next(), Some(0));
428 /// assert_eq!(iter.next(), Some(2));
429 /// assert_eq!(iter.next(), Some(4));
430 /// assert_eq!(iter.next(), None);
431 /// ```
432 #[inline]
433 #[stable(feature = "iterator_step_by", since = "1.28.0")]
434 #[rustc_non_const_trait_method]
435 fn step_by(self, step: usize) -> StepBy<Self>
436 where
437 Self: Sized,
438 {
439 StepBy::new(self, step)
440 }
441
442 /// Takes two iterators and creates a new iterator over both in sequence.
443 ///
444 /// `chain()` will return a new iterator which will first iterate over
445 /// values from the first iterator and then over values from the second
446 /// iterator.
447 ///
448 /// In other words, it links two iterators together, in a chain. 🔗
449 ///
450 /// [`once`] is commonly used to adapt a single value into a chain of
451 /// other kinds of iteration.
452 ///
453 /// # Examples
454 ///
455 /// Basic usage:
456 ///
457 /// ```
458 /// let s1 = "abc".chars();
459 /// let s2 = "def".chars();
460 ///
461 /// let mut iter = s1.chain(s2);
462 ///
463 /// assert_eq!(iter.next(), Some('a'));
464 /// assert_eq!(iter.next(), Some('b'));
465 /// assert_eq!(iter.next(), Some('c'));
466 /// assert_eq!(iter.next(), Some('d'));
467 /// assert_eq!(iter.next(), Some('e'));
468 /// assert_eq!(iter.next(), Some('f'));
469 /// assert_eq!(iter.next(), None);
470 /// ```
471 ///
472 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
473 /// anything that can be converted into an [`Iterator`], not just an
474 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
475 /// [`IntoIterator`], and so can be passed to `chain()` directly:
476 ///
477 /// ```
478 /// let a1 = [1, 2, 3];
479 /// let a2 = [4, 5, 6];
480 ///
481 /// let mut iter = a1.into_iter().chain(a2);
482 ///
483 /// assert_eq!(iter.next(), Some(1));
484 /// assert_eq!(iter.next(), Some(2));
485 /// assert_eq!(iter.next(), Some(3));
486 /// assert_eq!(iter.next(), Some(4));
487 /// assert_eq!(iter.next(), Some(5));
488 /// assert_eq!(iter.next(), Some(6));
489 /// assert_eq!(iter.next(), None);
490 /// ```
491 ///
492 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
493 ///
494 /// ```
495 /// #[cfg(windows)]
496 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
497 /// use std::os::windows::ffi::OsStrExt;
498 /// s.encode_wide().chain(std::iter::once(0)).collect()
499 /// }
500 /// ```
501 ///
502 /// [`once`]: crate::iter::once
503 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
504 #[inline]
505 #[stable(feature = "rust1", since = "1.0.0")]
506 #[rustc_non_const_trait_method]
507 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
508 where
509 Self: Sized,
510 U: IntoIterator<Item = Self::Item>,
511 {
512 Chain::new(self, other.into_iter())
513 }
514
515 /// 'Zips up' two iterators into a single iterator of pairs.
516 ///
517 /// `zip()` returns a new iterator that will iterate over two other
518 /// iterators, returning a tuple where the first element comes from the
519 /// first iterator, and the second element comes from the second iterator.
520 ///
521 /// In other words, it zips two iterators together, into a single one.
522 ///
523 /// If either iterator returns [`None`], [`next`] from the zipped iterator
524 /// will return [`None`].
525 /// If the zipped iterator has no more elements to return then each further attempt to advance
526 /// it will first try to advance the first iterator at most one time and if it still yielded an item
527 /// try to advance the second iterator at most one time.
528 ///
529 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
530 ///
531 /// [`unzip`]: Iterator::unzip
532 ///
533 /// # Examples
534 ///
535 /// Basic usage:
536 ///
537 /// ```
538 /// let s1 = "abc".chars();
539 /// let s2 = "def".chars();
540 ///
541 /// let mut iter = s1.zip(s2);
542 ///
543 /// assert_eq!(iter.next(), Some(('a', 'd')));
544 /// assert_eq!(iter.next(), Some(('b', 'e')));
545 /// assert_eq!(iter.next(), Some(('c', 'f')));
546 /// assert_eq!(iter.next(), None);
547 /// ```
548 ///
549 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
550 /// anything that can be converted into an [`Iterator`], not just an
551 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
552 /// [`IntoIterator`], and so can be passed to `zip()` directly:
553 ///
554 /// ```
555 /// let a1 = [1, 2, 3];
556 /// let a2 = [4, 5, 6];
557 ///
558 /// let mut iter = a1.into_iter().zip(a2);
559 ///
560 /// assert_eq!(iter.next(), Some((1, 4)));
561 /// assert_eq!(iter.next(), Some((2, 5)));
562 /// assert_eq!(iter.next(), Some((3, 6)));
563 /// assert_eq!(iter.next(), None);
564 /// ```
565 ///
566 /// `zip()` is often used to zip an infinite iterator to a finite one.
567 /// This works because the finite iterator will eventually return [`None`],
568 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
569 ///
570 /// ```
571 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
572 ///
573 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
574 ///
575 /// assert_eq!((0, 'f'), enumerate[0]);
576 /// assert_eq!((0, 'f'), zipper[0]);
577 ///
578 /// assert_eq!((1, 'o'), enumerate[1]);
579 /// assert_eq!((1, 'o'), zipper[1]);
580 ///
581 /// assert_eq!((2, 'o'), enumerate[2]);
582 /// assert_eq!((2, 'o'), zipper[2]);
583 /// ```
584 ///
585 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
586 ///
587 /// ```
588 /// use std::iter::zip;
589 ///
590 /// let a = [1, 2, 3];
591 /// let b = [2, 3, 4];
592 ///
593 /// let mut zipped = zip(
594 /// a.into_iter().map(|x| x * 2).skip(1),
595 /// b.into_iter().map(|x| x * 2).skip(1),
596 /// );
597 ///
598 /// assert_eq!(zipped.next(), Some((4, 6)));
599 /// assert_eq!(zipped.next(), Some((6, 8)));
600 /// assert_eq!(zipped.next(), None);
601 /// ```
602 ///
603 /// compared to:
604 ///
605 /// ```
606 /// # let a = [1, 2, 3];
607 /// # let b = [2, 3, 4];
608 /// #
609 /// let mut zipped = a
610 /// .into_iter()
611 /// .map(|x| x * 2)
612 /// .skip(1)
613 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
614 /// #
615 /// # assert_eq!(zipped.next(), Some((4, 6)));
616 /// # assert_eq!(zipped.next(), Some((6, 8)));
617 /// # assert_eq!(zipped.next(), None);
618 /// ```
619 ///
620 /// [`enumerate`]: Iterator::enumerate
621 /// [`next`]: Iterator::next
622 /// [`zip`]: crate::iter::zip
623 #[inline]
624 #[stable(feature = "rust1", since = "1.0.0")]
625 #[rustc_non_const_trait_method]
626 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
627 where
628 Self: Sized,
629 U: IntoIterator,
630 {
631 Zip::new(self, other.into_iter())
632 }
633
634 /// Creates a new iterator which places a copy of `separator` between items
635 /// of the original iterator.
636 ///
637 /// Specifically on fused iterators, it is guaranteed that the new iterator
638 /// places a copy of `separator` between adjacent `Some(_)` items. However,
639 /// for non-fused iterators, [`intersperse`] will create a new iterator that
640 /// is a fused version of the original iterator and place a copy of `separator`
641 /// between adjacent `Some(_)` items. This behavior for non-fused iterators
642 /// is subject to change.
643 ///
644 /// In case `separator` does not implement [`Clone`] or needs to be
645 /// computed every time, use [`intersperse_with`].
646 ///
647 /// # Examples
648 ///
649 /// Basic usage:
650 ///
651 /// ```
652 /// #![feature(iter_intersperse)]
653 ///
654 /// let mut a = [0, 1, 2].into_iter().intersperse(100);
655 /// assert_eq!(a.next(), Some(0)); // The first element from `a`.
656 /// assert_eq!(a.next(), Some(100)); // The separator.
657 /// assert_eq!(a.next(), Some(1)); // The next element from `a`.
658 /// assert_eq!(a.next(), Some(100)); // The separator.
659 /// assert_eq!(a.next(), Some(2)); // The last element from `a`.
660 /// assert_eq!(a.next(), None); // The iterator is finished.
661 /// ```
662 ///
663 /// `intersperse` can be very useful to join an iterator's items using a common element:
664 /// ```
665 /// #![feature(iter_intersperse)]
666 ///
667 /// let words = ["Hello", "World", "!"];
668 /// let hello: String = words.into_iter().intersperse(" ").collect();
669 /// assert_eq!(hello, "Hello World !");
670 /// ```
671 ///
672 /// [`Clone`]: crate::clone::Clone
673 /// [`intersperse`]: Iterator::intersperse
674 /// [`intersperse_with`]: Iterator::intersperse_with
675 #[inline]
676 #[unstable(feature = "iter_intersperse", issue = "79524")]
677 #[rustc_non_const_trait_method]
678 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
679 where
680 Self: Sized,
681 Self::Item: Clone,
682 {
683 Intersperse::new(self, separator)
684 }
685
686 /// Creates a new iterator which places an item generated by `separator`
687 /// between items of the original iterator.
688 ///
689 /// Specifically on fused iterators, it is guaranteed that the new iterator
690 /// places an item generated by `separator` between adjacent `Some(_)` items.
691 /// However, for non-fused iterators, [`intersperse_with`] will create a new
692 /// iterator that is a fused version of the original iterator and place an item
693 /// generated by `separator` between adjacent `Some(_)` items. This
694 /// behavior for non-fused iterators is subject to change.
695 ///
696 /// The `separator` closure will be called exactly once each time an item
697 /// is placed between two adjacent items from the underlying iterator;
698 /// specifically, the closure is not called if the underlying iterator yields
699 /// less than two items and after the last item is yielded.
700 ///
701 /// If the iterator's item implements [`Clone`], it may be easier to use
702 /// [`intersperse`].
703 ///
704 /// # Examples
705 ///
706 /// Basic usage:
707 ///
708 /// ```
709 /// #![feature(iter_intersperse)]
710 ///
711 /// #[derive(PartialEq, Debug)]
712 /// struct NotClone(usize);
713 ///
714 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
715 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
716 ///
717 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
718 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
719 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
720 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
721 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
722 /// assert_eq!(it.next(), None); // The iterator is finished.
723 /// ```
724 ///
725 /// `intersperse_with` can be used in situations where the separator needs
726 /// to be computed:
727 /// ```
728 /// #![feature(iter_intersperse)]
729 ///
730 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
731 ///
732 /// // The closure mutably borrows its context to generate an item.
733 /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();
734 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
735 ///
736 /// let result = src.intersperse_with(separator).collect::<String>();
737 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
738 /// ```
739 /// [`Clone`]: crate::clone::Clone
740 /// [`intersperse`]: Iterator::intersperse
741 /// [`intersperse_with`]: Iterator::intersperse_with
742 #[inline]
743 #[unstable(feature = "iter_intersperse", issue = "79524")]
744 #[rustc_non_const_trait_method]
745 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
746 where
747 Self: Sized,
748 G: FnMut() -> Self::Item,
749 {
750 IntersperseWith::new(self, separator)
751 }
752
753 /// Takes a closure and creates an iterator which calls that closure on each
754 /// element.
755 ///
756 /// `map()` transforms one iterator into another, by means of its argument:
757 /// something that implements [`FnMut`]. It produces a new iterator which
758 /// calls this closure on each element of the original iterator.
759 ///
760 /// If you are good at thinking in types, you can think of `map()` like this:
761 /// If you have an iterator that gives you elements of some type `A`, and
762 /// you want an iterator of some other type `B`, you can use `map()`,
763 /// passing a closure that takes an `A` and returns a `B`.
764 ///
765 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
766 /// lazy, it is best used when you're already working with other iterators.
767 /// If you're doing some sort of looping for a side effect, it's considered
768 /// more idiomatic to use [`for`] than `map()`.
769 ///
770 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
771 ///
772 /// # Examples
773 ///
774 /// Basic usage:
775 ///
776 /// ```
777 /// let a = [1, 2, 3];
778 ///
779 /// let mut iter = a.iter().map(|x| 2 * x);
780 ///
781 /// assert_eq!(iter.next(), Some(2));
782 /// assert_eq!(iter.next(), Some(4));
783 /// assert_eq!(iter.next(), Some(6));
784 /// assert_eq!(iter.next(), None);
785 /// ```
786 ///
787 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
788 ///
789 /// ```
790 /// # #![allow(unused_must_use)]
791 /// // don't do this:
792 /// (0..5).map(|x| println!("{x}"));
793 ///
794 /// // it won't even execute, as it is lazy. Rust will warn you about this.
795 ///
796 /// // Instead, use a for-loop:
797 /// for x in 0..5 {
798 /// println!("{x}");
799 /// }
800 /// ```
801 #[rustc_diagnostic_item = "IteratorMap"]
802 #[inline]
803 #[stable(feature = "rust1", since = "1.0.0")]
804 #[rustc_non_const_trait_method]
805 fn map<B, F>(self, f: F) -> Map<Self, F>
806 where
807 Self: Sized,
808 F: FnMut(Self::Item) -> B,
809 {
810 Map::new(self, f)
811 }
812
813 /// Calls a closure on each element of an iterator.
814 ///
815 /// This is equivalent to using a [`for`] loop on the iterator, although
816 /// `break` and `continue` are not possible from a closure. It's generally
817 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
818 /// when processing items at the end of longer iterator chains. In some
819 /// cases `for_each` may also be faster than a loop, because it will use
820 /// internal iteration on adapters like `Chain`.
821 ///
822 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
823 ///
824 /// # Examples
825 ///
826 /// Basic usage:
827 ///
828 /// ```
829 /// use std::sync::mpsc::channel;
830 ///
831 /// let (tx, rx) = channel();
832 /// (0..5).map(|x| x * 2 + 1)
833 /// .for_each(move |x| tx.send(x).unwrap());
834 ///
835 /// let v: Vec<_> = rx.iter().collect();
836 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
837 /// ```
838 ///
839 /// For such a small example, a `for` loop may be cleaner, but `for_each`
840 /// might be preferable to keep a functional style with longer iterators:
841 ///
842 /// ```
843 /// (0..5).flat_map(|x| (x * 100)..(x * 110))
844 /// .enumerate()
845 /// .filter(|&(i, x)| (i + x) % 3 == 0)
846 /// .for_each(|(i, x)| println!("{i}:{x}"));
847 /// ```
848 #[inline]
849 #[stable(feature = "iterator_for_each", since = "1.21.0")]
850 #[rustc_non_const_trait_method]
851 fn for_each<F>(self, f: F)
852 where
853 Self: Sized,
854 F: FnMut(Self::Item),
855 {
856 #[inline]
857 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
858 move |(), item| f(item)
859 }
860
861 self.fold((), call(f));
862 }
863
864 /// Creates an iterator which uses a closure to determine if an element
865 /// should be yielded.
866 ///
867 /// Given an element the closure must return `true` or `false`. The returned
868 /// iterator will yield only the elements for which the closure returns
869 /// `true`.
870 ///
871 /// # Examples
872 ///
873 /// Basic usage:
874 ///
875 /// ```
876 /// let a = [0i32, 1, 2];
877 ///
878 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
879 ///
880 /// assert_eq!(iter.next(), Some(1));
881 /// assert_eq!(iter.next(), Some(2));
882 /// assert_eq!(iter.next(), None);
883 /// ```
884 ///
885 /// Because the closure passed to `filter()` takes a reference, and many
886 /// iterators iterate over references, this leads to a possibly confusing
887 /// situation, where the type of the closure is a double reference:
888 ///
889 /// ```
890 /// let s = &[0, 1, 2];
891 ///
892 /// let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!
893 ///
894 /// assert_eq!(iter.next(), Some(&2));
895 /// assert_eq!(iter.next(), None);
896 /// ```
897 ///
898 /// It's common to instead use destructuring on the argument to strip away one:
899 ///
900 /// ```
901 /// let s = &[0, 1, 2];
902 ///
903 /// let mut iter = s.iter().filter(|&x| *x > 1); // both & and *
904 ///
905 /// assert_eq!(iter.next(), Some(&2));
906 /// assert_eq!(iter.next(), None);
907 /// ```
908 ///
909 /// or both:
910 ///
911 /// ```
912 /// let s = &[0, 1, 2];
913 ///
914 /// let mut iter = s.iter().filter(|&&x| x > 1); // two &s
915 ///
916 /// assert_eq!(iter.next(), Some(&2));
917 /// assert_eq!(iter.next(), None);
918 /// ```
919 ///
920 /// of these layers.
921 ///
922 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
923 #[inline]
924 #[stable(feature = "rust1", since = "1.0.0")]
925 #[rustc_diagnostic_item = "iter_filter"]
926 #[rustc_non_const_trait_method]
927 fn filter<P>(self, predicate: P) -> Filter<Self, P>
928 where
929 Self: Sized,
930 P: FnMut(&Self::Item) -> bool,
931 {
932 Filter::new(self, predicate)
933 }
934
935 /// Creates an iterator that both filters and maps.
936 ///
937 /// The returned iterator yields only the `value`s for which the supplied
938 /// closure returns `Some(value)`.
939 ///
940 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
941 /// concise. The example below shows how a `map().filter().map()` can be
942 /// shortened to a single call to `filter_map`.
943 ///
944 /// [`filter`]: Iterator::filter
945 /// [`map`]: Iterator::map
946 ///
947 /// # Examples
948 ///
949 /// Basic usage:
950 ///
951 /// ```
952 /// let a = ["1", "two", "NaN", "four", "5"];
953 ///
954 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
955 ///
956 /// assert_eq!(iter.next(), Some(1));
957 /// assert_eq!(iter.next(), Some(5));
958 /// assert_eq!(iter.next(), None);
959 /// ```
960 ///
961 /// Here's the same example, but with [`filter`] and [`map`]:
962 ///
963 /// ```
964 /// let a = ["1", "two", "NaN", "four", "5"];
965 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
966 /// assert_eq!(iter.next(), Some(1));
967 /// assert_eq!(iter.next(), Some(5));
968 /// assert_eq!(iter.next(), None);
969 /// ```
970 #[inline]
971 #[stable(feature = "rust1", since = "1.0.0")]
972 #[rustc_non_const_trait_method]
973 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
974 where
975 Self: Sized,
976 F: FnMut(Self::Item) -> Option<B>,
977 {
978 FilterMap::new(self, f)
979 }
980
981 /// Creates an iterator which gives the current iteration count as well as
982 /// the next value.
983 ///
984 /// The iterator returned yields pairs `(i, val)`, where `i` is the
985 /// current index of iteration and `val` is the value returned by the
986 /// iterator.
987 ///
988 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
989 /// different sized integer, the [`zip`] function provides similar
990 /// functionality.
991 ///
992 /// # Overflow Behavior
993 ///
994 /// The method does no guarding against overflows, so enumerating more than
995 /// [`usize::MAX`] elements either produces the wrong result or panics. If
996 /// overflow checks are enabled, a panic is guaranteed.
997 ///
998 /// # Panics
999 ///
1000 /// The returned iterator might panic if the to-be-returned index would
1001 /// overflow a [`usize`].
1002 ///
1003 /// [`zip`]: Iterator::zip
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 /// let a = ['a', 'b', 'c'];
1009 ///
1010 /// let mut iter = a.into_iter().enumerate();
1011 ///
1012 /// assert_eq!(iter.next(), Some((0, 'a')));
1013 /// assert_eq!(iter.next(), Some((1, 'b')));
1014 /// assert_eq!(iter.next(), Some((2, 'c')));
1015 /// assert_eq!(iter.next(), None);
1016 /// ```
1017 #[inline]
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 #[rustc_diagnostic_item = "enumerate_method"]
1020 #[rustc_non_const_trait_method]
1021 fn enumerate(self) -> Enumerate<Self>
1022 where
1023 Self: Sized,
1024 {
1025 Enumerate::new(self)
1026 }
1027
1028 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
1029 /// to look at the next element of the iterator without consuming it. See
1030 /// their documentation for more information.
1031 ///
1032 /// Note that the underlying iterator is still advanced when [`peek`] or
1033 /// [`peek_mut`] are called for the first time: In order to retrieve the
1034 /// next element, [`next`] is called on the underlying iterator, hence any
1035 /// side effects (i.e. anything other than fetching the next value) of
1036 /// the [`next`] method will occur.
1037 ///
1038 ///
1039 /// # Examples
1040 ///
1041 /// Basic usage:
1042 ///
1043 /// ```
1044 /// let xs = [1, 2, 3];
1045 ///
1046 /// let mut iter = xs.into_iter().peekable();
1047 ///
1048 /// // peek() lets us see into the future
1049 /// assert_eq!(iter.peek(), Some(&1));
1050 /// assert_eq!(iter.next(), Some(1));
1051 ///
1052 /// assert_eq!(iter.next(), Some(2));
1053 ///
1054 /// // we can peek() multiple times, the iterator won't advance
1055 /// assert_eq!(iter.peek(), Some(&3));
1056 /// assert_eq!(iter.peek(), Some(&3));
1057 ///
1058 /// assert_eq!(iter.next(), Some(3));
1059 ///
1060 /// // after the iterator is finished, so is peek()
1061 /// assert_eq!(iter.peek(), None);
1062 /// assert_eq!(iter.next(), None);
1063 /// ```
1064 ///
1065 /// Using [`peek_mut`] to mutate the next item without advancing the
1066 /// iterator:
1067 ///
1068 /// ```
1069 /// let xs = [1, 2, 3];
1070 ///
1071 /// let mut iter = xs.into_iter().peekable();
1072 ///
1073 /// // `peek_mut()` lets us see into the future
1074 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1075 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1076 /// assert_eq!(iter.next(), Some(1));
1077 ///
1078 /// if let Some(p) = iter.peek_mut() {
1079 /// assert_eq!(*p, 2);
1080 /// // put a value into the iterator
1081 /// *p = 1000;
1082 /// }
1083 ///
1084 /// // The value reappears as the iterator continues
1085 /// assert_eq!(iter.collect::<Vec<_>>(), vec![1000, 3]);
1086 /// ```
1087 /// [`peek`]: Peekable::peek
1088 /// [`peek_mut`]: Peekable::peek_mut
1089 /// [`next`]: Iterator::next
1090 #[inline]
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 #[rustc_non_const_trait_method]
1093 fn peekable(self) -> Peekable<Self>
1094 where
1095 Self: Sized,
1096 {
1097 Peekable::new(self)
1098 }
1099
1100 /// Creates an iterator that [`skip`]s elements based on a predicate.
1101 ///
1102 /// [`skip`]: Iterator::skip
1103 ///
1104 /// `skip_while()` takes a closure as an argument. It will call this
1105 /// closure on each element of the iterator, and ignore elements
1106 /// until it returns `false`.
1107 ///
1108 /// After `false` is returned, `skip_while()`'s job is over, and the
1109 /// rest of the elements are yielded.
1110 ///
1111 /// # Examples
1112 ///
1113 /// Basic usage:
1114 ///
1115 /// ```
1116 /// let a = [-1i32, 0, 1];
1117 ///
1118 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
1119 ///
1120 /// assert_eq!(iter.next(), Some(0));
1121 /// assert_eq!(iter.next(), Some(1));
1122 /// assert_eq!(iter.next(), None);
1123 /// ```
1124 ///
1125 /// Because the closure passed to `skip_while()` takes a reference, and many
1126 /// iterators iterate over references, this leads to a possibly confusing
1127 /// situation, where the type of the closure argument is a double reference:
1128 ///
1129 /// ```
1130 /// let s = &[-1, 0, 1];
1131 ///
1132 /// let mut iter = s.iter().skip_while(|x| **x < 0); // need two *s!
1133 ///
1134 /// assert_eq!(iter.next(), Some(&0));
1135 /// assert_eq!(iter.next(), Some(&1));
1136 /// assert_eq!(iter.next(), None);
1137 /// ```
1138 ///
1139 /// Stopping after an initial `false`:
1140 ///
1141 /// ```
1142 /// let a = [-1, 0, 1, -2];
1143 ///
1144 /// let mut iter = a.into_iter().skip_while(|&x| x < 0);
1145 ///
1146 /// assert_eq!(iter.next(), Some(0));
1147 /// assert_eq!(iter.next(), Some(1));
1148 ///
1149 /// // while this would have been false, since we already got a false,
1150 /// // skip_while() isn't used any more
1151 /// assert_eq!(iter.next(), Some(-2));
1152 ///
1153 /// assert_eq!(iter.next(), None);
1154 /// ```
1155 #[inline]
1156 #[doc(alias = "drop_while")]
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 #[rustc_non_const_trait_method]
1159 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1160 where
1161 Self: Sized,
1162 P: FnMut(&Self::Item) -> bool,
1163 {
1164 SkipWhile::new(self, predicate)
1165 }
1166
1167 /// Creates an iterator that yields elements based on a predicate.
1168 ///
1169 /// `take_while()` takes a closure as an argument. It will call this
1170 /// closure on each element of the iterator, and yield elements
1171 /// while it returns `true`.
1172 ///
1173 /// After `false` is returned, `take_while()`'s job is over, and the
1174 /// rest of the elements are ignored.
1175 ///
1176 /// # Examples
1177 ///
1178 /// Basic usage:
1179 ///
1180 /// ```
1181 /// let a = [-1i32, 0, 1];
1182 ///
1183 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1184 ///
1185 /// assert_eq!(iter.next(), Some(-1));
1186 /// assert_eq!(iter.next(), None);
1187 /// ```
1188 ///
1189 /// Because the closure passed to `take_while()` takes a reference, and many
1190 /// iterators iterate over references, this leads to a possibly confusing
1191 /// situation, where the type of the closure is a double reference:
1192 ///
1193 /// ```
1194 /// let s = &[-1, 0, 1];
1195 ///
1196 /// let mut iter = s.iter().take_while(|x| **x < 0); // need two *s!
1197 ///
1198 /// assert_eq!(iter.next(), Some(&-1));
1199 /// assert_eq!(iter.next(), None);
1200 /// ```
1201 ///
1202 /// Stopping after an initial `false`:
1203 ///
1204 /// ```
1205 /// let a = [-1, 0, 1, -2];
1206 ///
1207 /// let mut iter = a.into_iter().take_while(|&x| x < 0);
1208 ///
1209 /// assert_eq!(iter.next(), Some(-1));
1210 ///
1211 /// // We have more elements that are less than zero, but since we already
1212 /// // got a false, take_while() ignores the remaining elements.
1213 /// assert_eq!(iter.next(), None);
1214 /// ```
1215 ///
1216 /// Because `take_while()` needs to look at the value in order to see if it
1217 /// should be included or not, consuming iterators will see that it is
1218 /// removed:
1219 ///
1220 /// ```
1221 /// let a = [1, 2, 3, 4];
1222 /// let mut iter = a.into_iter();
1223 ///
1224 /// let result: Vec<i32> = iter.by_ref().take_while(|&n| n != 3).collect();
1225 ///
1226 /// assert_eq!(result, [1, 2]);
1227 ///
1228 /// let result: Vec<i32> = iter.collect();
1229 ///
1230 /// assert_eq!(result, [4]);
1231 /// ```
1232 ///
1233 /// The `3` is no longer there, because it was consumed in order to see if
1234 /// the iteration should stop, but wasn't placed back into the iterator.
1235 #[inline]
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 #[rustc_non_const_trait_method]
1238 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1239 where
1240 Self: Sized,
1241 P: FnMut(&Self::Item) -> bool,
1242 {
1243 TakeWhile::new(self, predicate)
1244 }
1245
1246 /// Creates an iterator that both yields elements based on a predicate and maps.
1247 ///
1248 /// `map_while()` takes a closure as an argument. It will call this
1249 /// closure on each element of the iterator, and yield elements
1250 /// while it returns [`Some(_)`][`Some`].
1251 ///
1252 /// # Examples
1253 ///
1254 /// Basic usage:
1255 ///
1256 /// ```
1257 /// let a = [-1i32, 4, 0, 1];
1258 ///
1259 /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));
1260 ///
1261 /// assert_eq!(iter.next(), Some(-16));
1262 /// assert_eq!(iter.next(), Some(4));
1263 /// assert_eq!(iter.next(), None);
1264 /// ```
1265 ///
1266 /// Here's the same example, but with [`take_while`] and [`map`]:
1267 ///
1268 /// [`take_while`]: Iterator::take_while
1269 /// [`map`]: Iterator::map
1270 ///
1271 /// ```
1272 /// let a = [-1i32, 4, 0, 1];
1273 ///
1274 /// let mut iter = a.into_iter()
1275 /// .map(|x| 16i32.checked_div(x))
1276 /// .take_while(|x| x.is_some())
1277 /// .map(|x| x.unwrap());
1278 ///
1279 /// assert_eq!(iter.next(), Some(-16));
1280 /// assert_eq!(iter.next(), Some(4));
1281 /// assert_eq!(iter.next(), None);
1282 /// ```
1283 ///
1284 /// Stopping after an initial [`None`]:
1285 ///
1286 /// ```
1287 /// let a = [0, 1, 2, -3, 4, 5, -6];
1288 ///
1289 /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());
1290 /// let vec: Vec<_> = iter.collect();
1291 ///
1292 /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`
1293 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1294 /// assert_eq!(vec, [0, 1, 2]);
1295 /// ```
1296 ///
1297 /// Because `map_while()` needs to look at the value in order to see if it
1298 /// should be included or not, consuming iterators will see that it is
1299 /// removed:
1300 ///
1301 /// ```
1302 /// let a = [1, 2, -3, 4];
1303 /// let mut iter = a.into_iter();
1304 ///
1305 /// let result: Vec<u32> = iter.by_ref()
1306 /// .map_while(|n| u32::try_from(n).ok())
1307 /// .collect();
1308 ///
1309 /// assert_eq!(result, [1, 2]);
1310 ///
1311 /// let result: Vec<i32> = iter.collect();
1312 ///
1313 /// assert_eq!(result, [4]);
1314 /// ```
1315 ///
1316 /// The `-3` is no longer there, because it was consumed in order to see if
1317 /// the iteration should stop, but wasn't placed back into the iterator.
1318 ///
1319 /// Note that unlike [`take_while`] this iterator is **not** fused.
1320 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1321 /// If you need a fused iterator, use [`fuse`].
1322 ///
1323 /// [`fuse`]: Iterator::fuse
1324 #[inline]
1325 #[stable(feature = "iter_map_while", since = "1.57.0")]
1326 #[rustc_non_const_trait_method]
1327 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1328 where
1329 Self: Sized,
1330 P: FnMut(Self::Item) -> Option<B>,
1331 {
1332 MapWhile::new(self, predicate)
1333 }
1334
1335 /// Creates an iterator that skips the first `n` elements.
1336 ///
1337 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1338 /// iterator is reached (whichever happens first). After that, all the remaining
1339 /// elements are yielded. In particular, if the original iterator is too short,
1340 /// then the returned iterator is empty.
1341 ///
1342 /// Rather than overriding this method directly, instead override the `nth` method.
1343 ///
1344 /// # Examples
1345 ///
1346 /// ```
1347 /// let a = [1, 2, 3];
1348 ///
1349 /// let mut iter = a.into_iter().skip(2);
1350 ///
1351 /// assert_eq!(iter.next(), Some(3));
1352 /// assert_eq!(iter.next(), None);
1353 /// ```
1354 #[inline]
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 #[rustc_non_const_trait_method]
1357 fn skip(self, n: usize) -> Skip<Self>
1358 where
1359 Self: Sized,
1360 {
1361 Skip::new(self, n)
1362 }
1363
1364 /// Creates an iterator that yields the first `n` elements, or fewer
1365 /// if the underlying iterator ends sooner.
1366 ///
1367 /// `take(n)` yields elements until `n` elements are yielded or the end of
1368 /// the iterator is reached (whichever happens first).
1369 /// The returned iterator is a prefix of length `n` if the original iterator
1370 /// contains at least `n` elements, otherwise it contains all of the
1371 /// (fewer than `n`) elements of the original iterator.
1372 ///
1373 /// # Examples
1374 ///
1375 /// Basic usage:
1376 ///
1377 /// ```
1378 /// let a = [1, 2, 3];
1379 ///
1380 /// let mut iter = a.into_iter().take(2);
1381 ///
1382 /// assert_eq!(iter.next(), Some(1));
1383 /// assert_eq!(iter.next(), Some(2));
1384 /// assert_eq!(iter.next(), None);
1385 /// ```
1386 ///
1387 /// `take()` is often used with an infinite iterator, to make it finite:
1388 ///
1389 /// ```
1390 /// let mut iter = (0..).take(3);
1391 ///
1392 /// assert_eq!(iter.next(), Some(0));
1393 /// assert_eq!(iter.next(), Some(1));
1394 /// assert_eq!(iter.next(), Some(2));
1395 /// assert_eq!(iter.next(), None);
1396 /// ```
1397 ///
1398 /// If less than `n` elements are available,
1399 /// `take` will limit itself to the size of the underlying iterator:
1400 ///
1401 /// ```
1402 /// let v = [1, 2];
1403 /// let mut iter = v.into_iter().take(5);
1404 /// assert_eq!(iter.next(), Some(1));
1405 /// assert_eq!(iter.next(), Some(2));
1406 /// assert_eq!(iter.next(), None);
1407 /// ```
1408 ///
1409 /// Use [`by_ref`] to take from the iterator without consuming it, and then
1410 /// continue using the original iterator:
1411 ///
1412 /// ```
1413 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1414 ///
1415 /// // Take the first two words.
1416 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1417 /// assert_eq!(hello_world, vec!["hello", "world"]);
1418 ///
1419 /// // Collect the rest of the words.
1420 /// // We can only do this because we used `by_ref` earlier.
1421 /// let of_rust: Vec<_> = words.collect();
1422 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1423 /// ```
1424 ///
1425 /// [`by_ref`]: Iterator::by_ref
1426 #[doc(alias = "limit")]
1427 #[inline]
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 #[rustc_non_const_trait_method]
1430 fn take(self, n: usize) -> Take<Self>
1431 where
1432 Self: Sized,
1433 {
1434 Take::new(self, n)
1435 }
1436
1437 /// An iterator adapter which, like [`fold`], holds internal state, but
1438 /// unlike [`fold`], produces a new iterator.
1439 ///
1440 /// [`fold`]: Iterator::fold
1441 ///
1442 /// `scan()` takes two arguments: an initial value which seeds the internal
1443 /// state, and a closure with two arguments, the first being a mutable
1444 /// reference to the internal state and the second an iterator element.
1445 /// The closure can assign to the internal state to share state between
1446 /// iterations.
1447 ///
1448 /// On iteration, the closure will be applied to each element of the
1449 /// iterator and the return value from the closure, an [`Option`], is
1450 /// returned by the `next` method. Thus the closure can return
1451 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1452 ///
1453 /// # Examples
1454 ///
1455 /// ```
1456 /// let a = [1, 2, 3, 4];
1457 ///
1458 /// let mut iter = a.into_iter().scan(1, |state, x| {
1459 /// // each iteration, we'll multiply the state by the element ...
1460 /// *state = *state * x;
1461 ///
1462 /// // ... and terminate if the state exceeds 6
1463 /// if *state > 6 {
1464 /// return None;
1465 /// }
1466 /// // ... else yield the negation of the state
1467 /// Some(-*state)
1468 /// });
1469 ///
1470 /// assert_eq!(iter.next(), Some(-1));
1471 /// assert_eq!(iter.next(), Some(-2));
1472 /// assert_eq!(iter.next(), Some(-6));
1473 /// assert_eq!(iter.next(), None);
1474 /// ```
1475 #[inline]
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 #[rustc_non_const_trait_method]
1478 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1479 where
1480 Self: Sized,
1481 F: FnMut(&mut St, Self::Item) -> Option<B>,
1482 {
1483 Scan::new(self, initial_state, f)
1484 }
1485
1486 /// Creates an iterator that works like map, but flattens nested structure.
1487 ///
1488 /// The [`map`] adapter is very useful, but only when the closure
1489 /// argument produces values. If it produces an iterator instead, there's
1490 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1491 /// on its own.
1492 ///
1493 /// You can think of `flat_map(f)` as the semantic equivalent
1494 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1495 ///
1496 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1497 /// one item for each element, and `flat_map()`'s closure returns an
1498 /// iterator for each element.
1499 ///
1500 /// [`map`]: Iterator::map
1501 /// [`flatten`]: Iterator::flatten
1502 ///
1503 /// # Examples
1504 ///
1505 /// ```
1506 /// let words = ["alpha", "beta", "gamma"];
1507 ///
1508 /// // chars() returns an iterator
1509 /// let merged: String = words.iter()
1510 /// .flat_map(|s| s.chars())
1511 /// .collect();
1512 /// assert_eq!(merged, "alphabetagamma");
1513 /// ```
1514 #[inline]
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 #[rustc_non_const_trait_method]
1517 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1518 where
1519 Self: Sized,
1520 U: IntoIterator,
1521 F: FnMut(Self::Item) -> U,
1522 {
1523 FlatMap::new(self, f)
1524 }
1525
1526 /// Creates an iterator that flattens nested structure.
1527 ///
1528 /// This is useful when you have an iterator of iterators or an iterator of
1529 /// things that can be turned into iterators and you want to remove one
1530 /// level of indirection.
1531 ///
1532 /// # Examples
1533 ///
1534 /// Basic usage:
1535 ///
1536 /// ```
1537 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1538 /// let flattened: Vec<_> = data.into_iter().flatten().collect();
1539 /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
1540 /// ```
1541 ///
1542 /// Mapping and then flattening:
1543 ///
1544 /// ```
1545 /// let words = ["alpha", "beta", "gamma"];
1546 ///
1547 /// // chars() returns an iterator
1548 /// let merged: String = words.iter()
1549 /// .map(|s| s.chars())
1550 /// .flatten()
1551 /// .collect();
1552 /// assert_eq!(merged, "alphabetagamma");
1553 /// ```
1554 ///
1555 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1556 /// in this case since it conveys intent more clearly:
1557 ///
1558 /// ```
1559 /// let words = ["alpha", "beta", "gamma"];
1560 ///
1561 /// // chars() returns an iterator
1562 /// let merged: String = words.iter()
1563 /// .flat_map(|s| s.chars())
1564 /// .collect();
1565 /// assert_eq!(merged, "alphabetagamma");
1566 /// ```
1567 ///
1568 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1569 ///
1570 /// ```
1571 /// let options = vec![Some(123), Some(321), None, Some(231)];
1572 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1573 /// assert_eq!(flattened_options, [123, 321, 231]);
1574 ///
1575 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1576 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1577 /// assert_eq!(flattened_results, [123, 321, 231]);
1578 /// ```
1579 ///
1580 /// Flattening only removes one level of nesting at a time:
1581 ///
1582 /// ```
1583 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1584 ///
1585 /// let d2: Vec<_> = d3.into_iter().flatten().collect();
1586 /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
1587 ///
1588 /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();
1589 /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
1590 /// ```
1591 ///
1592 /// Here we see that `flatten()` does not perform a "deep" flatten.
1593 /// Instead, only one level of nesting is removed. That is, if you
1594 /// `flatten()` a three-dimensional array, the result will be
1595 /// two-dimensional and not one-dimensional. To get a one-dimensional
1596 /// structure, you have to `flatten()` again.
1597 ///
1598 /// [`flat_map()`]: Iterator::flat_map
1599 #[inline]
1600 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1601 #[rustc_non_const_trait_method]
1602 fn flatten(self) -> Flatten<Self>
1603 where
1604 Self: Sized,
1605 Self::Item: IntoIterator,
1606 {
1607 Flatten::new(self)
1608 }
1609
1610 /// Calls the given function `f` for each contiguous window of size `N` over
1611 /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],
1612 /// the windows during mapping overlap as well.
1613 ///
1614 /// In the following example, the closure is called three times with the
1615 /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
1616 ///
1617 /// ```
1618 /// #![feature(iter_map_windows)]
1619 ///
1620 /// let strings = "abcd".chars()
1621 /// .map_windows(|[x, y]| format!("{}+{}", x, y))
1622 /// .collect::<Vec<String>>();
1623 ///
1624 /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);
1625 /// ```
1626 ///
1627 /// Note that the const parameter `N` is usually inferred by the
1628 /// destructured argument in the closure.
1629 ///
1630 /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
1631 /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
1632 /// empty iterator.
1633 ///
1634 /// The returned iterator implements [`FusedIterator`], because once `self`
1635 /// returns `None`, even if it returns a `Some(T)` again in the next iterations,
1636 /// we cannot put it into a contiguous array buffer, and thus the returned iterator
1637 /// should be fused.
1638 ///
1639 /// [`slice::windows()`]: slice::windows
1640 /// [`FusedIterator`]: crate::iter::FusedIterator
1641 ///
1642 /// # Panics
1643 ///
1644 /// Panics if `N` is zero. This check will most probably get changed to a
1645 /// compile time error before this method gets stabilized.
1646 ///
1647 /// ```should_panic
1648 /// #![feature(iter_map_windows)]
1649 ///
1650 /// let iter = std::iter::repeat(0).map_windows(|&[]| ());
1651 /// ```
1652 ///
1653 /// # Examples
1654 ///
1655 /// Building the sums of neighboring numbers.
1656 ///
1657 /// ```
1658 /// #![feature(iter_map_windows)]
1659 ///
1660 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1661 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1662 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1663 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1664 /// assert_eq!(it.next(), None);
1665 /// ```
1666 ///
1667 /// Since the elements in the following example implement `Copy`, we can
1668 /// just copy the array and get an iterator over the windows.
1669 ///
1670 /// ```
1671 /// #![feature(iter_map_windows)]
1672 ///
1673 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1674 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1675 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1676 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1677 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1678 /// assert_eq!(it.next(), None);
1679 /// ```
1680 ///
1681 /// You can also use this function to check the sortedness of an iterator.
1682 /// For the simple case, rather use [`Iterator::is_sorted`].
1683 ///
1684 /// ```
1685 /// #![feature(iter_map_windows)]
1686 ///
1687 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1688 /// .map_windows(|[a, b]| a <= b);
1689 ///
1690 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1691 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1692 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1693 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1694 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1695 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1696 /// assert_eq!(it.next(), None);
1697 /// ```
1698 ///
1699 /// For non-fused iterators, they are fused after `map_windows`.
1700 ///
1701 /// ```
1702 /// #![feature(iter_map_windows)]
1703 ///
1704 /// #[derive(Default)]
1705 /// struct NonFusedIterator {
1706 /// state: i32,
1707 /// }
1708 ///
1709 /// impl Iterator for NonFusedIterator {
1710 /// type Item = i32;
1711 ///
1712 /// fn next(&mut self) -> Option<i32> {
1713 /// let val = self.state;
1714 /// self.state = self.state + 1;
1715 ///
1716 /// // yields `0..5` first, then only even numbers since `6..`.
1717 /// if val < 5 || val % 2 == 0 {
1718 /// Some(val)
1719 /// } else {
1720 /// None
1721 /// }
1722 /// }
1723 /// }
1724 ///
1725 ///
1726 /// let mut iter = NonFusedIterator::default();
1727 ///
1728 /// // yields 0..5 first.
1729 /// assert_eq!(iter.next(), Some(0));
1730 /// assert_eq!(iter.next(), Some(1));
1731 /// assert_eq!(iter.next(), Some(2));
1732 /// assert_eq!(iter.next(), Some(3));
1733 /// assert_eq!(iter.next(), Some(4));
1734 /// // then we can see our iterator going back and forth
1735 /// assert_eq!(iter.next(), None);
1736 /// assert_eq!(iter.next(), Some(6));
1737 /// assert_eq!(iter.next(), None);
1738 /// assert_eq!(iter.next(), Some(8));
1739 /// assert_eq!(iter.next(), None);
1740 ///
1741 /// // however, with `.map_windows()`, it is fused.
1742 /// let mut iter = NonFusedIterator::default()
1743 /// .map_windows(|arr: &[_; 2]| *arr);
1744 ///
1745 /// assert_eq!(iter.next(), Some([0, 1]));
1746 /// assert_eq!(iter.next(), Some([1, 2]));
1747 /// assert_eq!(iter.next(), Some([2, 3]));
1748 /// assert_eq!(iter.next(), Some([3, 4]));
1749 /// assert_eq!(iter.next(), None);
1750 ///
1751 /// // it will always return `None` after the first time.
1752 /// assert_eq!(iter.next(), None);
1753 /// assert_eq!(iter.next(), None);
1754 /// assert_eq!(iter.next(), None);
1755 /// ```
1756 #[inline]
1757 #[unstable(feature = "iter_map_windows", issue = "87155")]
1758 #[rustc_non_const_trait_method]
1759 fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
1760 where
1761 Self: Sized,
1762 F: FnMut(&[Self::Item; N]) -> R,
1763 {
1764 MapWindows::new(self, f)
1765 }
1766
1767 /// Creates an iterator which ends after the first [`None`].
1768 ///
1769 /// After an iterator returns [`None`], future calls may or may not yield
1770 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1771 /// [`None`] is given, it will always return [`None`] forever.
1772 ///
1773 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1774 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1775 /// if the [`FusedIterator`] trait is improperly implemented.
1776 ///
1777 /// [`Some(T)`]: Some
1778 /// [`FusedIterator`]: crate::iter::FusedIterator
1779 ///
1780 /// # Examples
1781 ///
1782 /// ```
1783 /// // an iterator which alternates between Some and None
1784 /// struct Alternate {
1785 /// state: i32,
1786 /// }
1787 ///
1788 /// impl Iterator for Alternate {
1789 /// type Item = i32;
1790 ///
1791 /// fn next(&mut self) -> Option<i32> {
1792 /// let val = self.state;
1793 /// self.state = self.state + 1;
1794 ///
1795 /// // if it's even, Some(i32), else None
1796 /// (val % 2 == 0).then_some(val)
1797 /// }
1798 /// }
1799 ///
1800 /// let mut iter = Alternate { state: 0 };
1801 ///
1802 /// // we can see our iterator going back and forth
1803 /// assert_eq!(iter.next(), Some(0));
1804 /// assert_eq!(iter.next(), None);
1805 /// assert_eq!(iter.next(), Some(2));
1806 /// assert_eq!(iter.next(), None);
1807 ///
1808 /// // however, once we fuse it...
1809 /// let mut iter = iter.fuse();
1810 ///
1811 /// assert_eq!(iter.next(), Some(4));
1812 /// assert_eq!(iter.next(), None);
1813 ///
1814 /// // it will always return `None` after the first time.
1815 /// assert_eq!(iter.next(), None);
1816 /// assert_eq!(iter.next(), None);
1817 /// assert_eq!(iter.next(), None);
1818 /// ```
1819 #[inline]
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 #[rustc_non_const_trait_method]
1822 fn fuse(self) -> Fuse<Self>
1823 where
1824 Self: Sized,
1825 {
1826 Fuse::new(self)
1827 }
1828
1829 /// Does something with each element of an iterator, passing the value on.
1830 ///
1831 /// When using iterators, you'll often chain several of them together.
1832 /// While working on such code, you might want to check out what's
1833 /// happening at various parts in the pipeline. To do that, insert
1834 /// a call to `inspect()`.
1835 ///
1836 /// It's more common for `inspect()` to be used as a debugging tool than to
1837 /// exist in your final code, but applications may find it useful in certain
1838 /// situations when errors need to be logged before being discarded.
1839 ///
1840 /// # Examples
1841 ///
1842 /// Basic usage:
1843 ///
1844 /// ```
1845 /// let a = [1, 4, 2, 3];
1846 ///
1847 /// // this iterator sequence is complex.
1848 /// let sum = a.iter()
1849 /// .cloned()
1850 /// .filter(|x| x % 2 == 0)
1851 /// .fold(0, |sum, i| sum + i);
1852 ///
1853 /// println!("{sum}");
1854 ///
1855 /// // let's add some inspect() calls to investigate what's happening
1856 /// let sum = a.iter()
1857 /// .cloned()
1858 /// .inspect(|x| println!("about to filter: {x}"))
1859 /// .filter(|x| x % 2 == 0)
1860 /// .inspect(|x| println!("made it through filter: {x}"))
1861 /// .fold(0, |sum, i| sum + i);
1862 ///
1863 /// println!("{sum}");
1864 /// ```
1865 ///
1866 /// This will print:
1867 ///
1868 /// ```text
1869 /// 6
1870 /// about to filter: 1
1871 /// about to filter: 4
1872 /// made it through filter: 4
1873 /// about to filter: 2
1874 /// made it through filter: 2
1875 /// about to filter: 3
1876 /// 6
1877 /// ```
1878 ///
1879 /// Logging errors before discarding them:
1880 ///
1881 /// ```
1882 /// let lines = ["1", "2", "a"];
1883 ///
1884 /// let sum: i32 = lines
1885 /// .iter()
1886 /// .map(|line| line.parse::<i32>())
1887 /// .inspect(|num| {
1888 /// if let Err(ref e) = *num {
1889 /// println!("Parsing error: {e}");
1890 /// }
1891 /// })
1892 /// .filter_map(Result::ok)
1893 /// .sum();
1894 ///
1895 /// println!("Sum: {sum}");
1896 /// ```
1897 ///
1898 /// This will print:
1899 ///
1900 /// ```text
1901 /// Parsing error: invalid digit found in string
1902 /// Sum: 3
1903 /// ```
1904 #[inline]
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 #[rustc_non_const_trait_method]
1907 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1908 where
1909 Self: Sized,
1910 F: FnMut(&Self::Item),
1911 {
1912 Inspect::new(self, f)
1913 }
1914
1915 /// Creates a "by reference" adapter for this instance of `Iterator`.
1916 ///
1917 /// Consuming method calls (direct or indirect calls to `next`)
1918 /// on the "by reference" adapter will consume the original iterator,
1919 /// but ownership-taking methods (those with a `self` parameter)
1920 /// only take ownership of the "by reference" iterator.
1921 ///
1922 /// This is useful for applying ownership-taking methods
1923 /// (such as `take` in the example below)
1924 /// without giving up ownership of the original iterator,
1925 /// so you can use the original iterator afterwards.
1926 ///
1927 /// Uses [`impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}`](Iterator#impl-Iterator-for-%26mut+I).
1928 ///
1929 /// # Examples
1930 ///
1931 /// ```
1932 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1933 ///
1934 /// // Take the first two words.
1935 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1936 /// assert_eq!(hello_world, vec!["hello", "world"]);
1937 ///
1938 /// // Collect the rest of the words.
1939 /// // We can only do this because we used `by_ref` earlier.
1940 /// let of_rust: Vec<_> = words.collect();
1941 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1942 /// ```
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 fn by_ref(&mut self) -> &mut Self
1945 where
1946 Self: Sized,
1947 {
1948 self
1949 }
1950
1951 /// Transforms an iterator into a collection.
1952 ///
1953 /// `collect()` takes ownership of an iterator and produces whichever
1954 /// collection type you request. The iterator itself carries no knowledge of
1955 /// the eventual container; the target collection is chosen entirely by the
1956 /// type you ask `collect()` to return. This makes `collect()` one of the
1957 /// more powerful methods in the standard library, and it shows up in a wide
1958 /// variety of contexts.
1959 ///
1960 /// The most basic pattern in which `collect()` is used is to turn one
1961 /// collection into another. You take a collection, call [`iter`] on it,
1962 /// do a bunch of transformations, and then `collect()` at the end.
1963 ///
1964 /// `collect()` can also create instances of types that are not typical
1965 /// collections. For example, a [`String`] can be built from [`char`]s,
1966 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1967 /// into `Result<Collection<T>, E>`. See the examples below for more.
1968 ///
1969 /// Because `collect()` is so general, it can cause problems with type
1970 /// inference. As such, `collect()` is one of the few times you'll see
1971 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1972 /// helps the inference algorithm understand specifically which collection
1973 /// you're trying to collect into.
1974 ///
1975 /// # Examples
1976 ///
1977 /// Basic usage:
1978 ///
1979 /// ```
1980 /// let a = [1, 2, 3];
1981 ///
1982 /// let doubled: Vec<i32> = a.iter()
1983 /// .map(|x| x * 2)
1984 /// .collect();
1985 ///
1986 /// assert_eq!(vec![2, 4, 6], doubled);
1987 /// ```
1988 ///
1989 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1990 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1991 ///
1992 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1993 ///
1994 /// ```
1995 /// use std::collections::VecDeque;
1996 ///
1997 /// let a = [1, 2, 3];
1998 ///
1999 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
2000 ///
2001 /// assert_eq!(2, doubled[0]);
2002 /// assert_eq!(4, doubled[1]);
2003 /// assert_eq!(6, doubled[2]);
2004 /// ```
2005 ///
2006 /// Using the 'turbofish' instead of annotating `doubled`:
2007 ///
2008 /// ```
2009 /// let a = [1, 2, 3];
2010 ///
2011 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
2012 ///
2013 /// assert_eq!(vec![2, 4, 6], doubled);
2014 /// ```
2015 ///
2016 /// Because `collect()` only cares about what you're collecting into, you can
2017 /// still use a partial type hint, `_`, with the turbofish:
2018 ///
2019 /// ```
2020 /// let a = [1, 2, 3];
2021 ///
2022 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
2023 ///
2024 /// assert_eq!(vec![2, 4, 6], doubled);
2025 /// ```
2026 ///
2027 /// Using `collect()` to make a [`String`]:
2028 ///
2029 /// ```
2030 /// let chars = ['g', 'd', 'k', 'k', 'n'];
2031 ///
2032 /// let hello: String = chars.into_iter()
2033 /// .map(|x| x as u8)
2034 /// .map(|x| (x + 1) as char)
2035 /// .collect();
2036 ///
2037 /// assert_eq!("hello", hello);
2038 /// ```
2039 ///
2040 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
2041 /// see if any of them failed:
2042 ///
2043 /// ```
2044 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2045 ///
2046 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2047 ///
2048 /// // gives us the first error
2049 /// assert_eq!(Err("nope"), result);
2050 ///
2051 /// let results = [Ok(1), Ok(3)];
2052 ///
2053 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2054 ///
2055 /// // gives us the list of answers
2056 /// assert_eq!(Ok(vec![1, 3]), result);
2057 /// ```
2058 ///
2059 /// [`iter`]: Iterator::next
2060 /// [`String`]: ../../std/string/struct.String.html
2061 /// [`char`]: type@char
2062 #[inline]
2063 #[stable(feature = "rust1", since = "1.0.0")]
2064 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2065 #[rustc_diagnostic_item = "iterator_collect_fn"]
2066 #[rustc_non_const_trait_method]
2067 fn collect<B: FromIterator<Self::Item>>(self) -> B
2068 where
2069 Self: Sized,
2070 {
2071 // This is too aggressive to turn on for everything all the time, but PR#137908
2072 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2073 // so this will help catch such things in debug-assertions-std runners,
2074 // even if users won't actually ever see it.
2075 if cfg!(debug_assertions) {
2076 let hint = self.size_hint();
2077 assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
2078 }
2079
2080 FromIterator::from_iter(self)
2081 }
2082
2083 /// Fallibly transforms an iterator into a collection, short circuiting if
2084 /// a failure is encountered.
2085 ///
2086 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
2087 /// conversions during collection. Its main use case is simplifying conversions from
2088 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
2089 /// types (e.g. [`Result`]).
2090 ///
2091 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
2092 /// only the inner type produced on `Try::Output` must implement it. Concretely,
2093 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
2094 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
2095 ///
2096 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
2097 /// may continue to be used, in which case it will continue iterating starting after the element that
2098 /// triggered the failure. See the last example below for an example of how this works.
2099 ///
2100 /// # Examples
2101 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
2102 /// ```
2103 /// #![feature(iterator_try_collect)]
2104 ///
2105 /// let u = vec![Some(1), Some(2), Some(3)];
2106 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2107 /// assert_eq!(v, Some(vec![1, 2, 3]));
2108 /// ```
2109 ///
2110 /// Failing to collect in the same way:
2111 /// ```
2112 /// #![feature(iterator_try_collect)]
2113 ///
2114 /// let u = vec![Some(1), Some(2), None, Some(3)];
2115 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2116 /// assert_eq!(v, None);
2117 /// ```
2118 ///
2119 /// A similar example, but with `Result`:
2120 /// ```
2121 /// #![feature(iterator_try_collect)]
2122 ///
2123 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
2124 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2125 /// assert_eq!(v, Ok(vec![1, 2, 3]));
2126 ///
2127 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
2128 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2129 /// assert_eq!(v, Err(()));
2130 /// ```
2131 ///
2132 /// Finally, even [`ControlFlow`] works, despite the fact that it
2133 /// doesn't implement [`FromIterator`]. Note also that the iterator can
2134 /// continue to be used, even if a failure is encountered:
2135 ///
2136 /// ```
2137 /// #![feature(iterator_try_collect)]
2138 ///
2139 /// use core::ops::ControlFlow::{Break, Continue};
2140 ///
2141 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
2142 /// let mut it = u.into_iter();
2143 ///
2144 /// let v = it.try_collect::<Vec<_>>();
2145 /// assert_eq!(v, Break(3));
2146 ///
2147 /// let v = it.try_collect::<Vec<_>>();
2148 /// assert_eq!(v, Continue(vec![4, 5]));
2149 /// ```
2150 ///
2151 /// [`collect`]: Iterator::collect
2152 #[inline]
2153 #[unstable(feature = "iterator_try_collect", issue = "94047")]
2154 #[rustc_non_const_trait_method]
2155 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
2156 where
2157 Self: Sized,
2158 Self::Item: Try<Residual: Residual<B>>,
2159 B: FromIterator<<Self::Item as Try>::Output>,
2160 {
2161 try_process(ByRefSized(self), |i| i.collect())
2162 }
2163
2164 /// Collects all the items from an iterator into a collection.
2165 ///
2166 /// This method consumes the iterator and adds all its items to the
2167 /// passed collection. The collection is then returned, so the call chain
2168 /// can be continued.
2169 ///
2170 /// This is useful when you already have a collection and want to add
2171 /// the iterator items to it.
2172 ///
2173 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
2174 /// but instead of being called on a collection, it's called on an iterator.
2175 ///
2176 /// # Examples
2177 ///
2178 /// Basic usage:
2179 ///
2180 /// ```
2181 /// #![feature(iter_collect_into)]
2182 ///
2183 /// let a = [1, 2, 3];
2184 /// let mut vec: Vec::<i32> = vec![0, 1];
2185 ///
2186 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2187 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2188 ///
2189 /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
2190 /// ```
2191 ///
2192 /// `Vec` can have a manual set capacity to avoid reallocating it:
2193 ///
2194 /// ```
2195 /// #![feature(iter_collect_into)]
2196 ///
2197 /// let a = [1, 2, 3];
2198 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2199 ///
2200 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2201 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2202 ///
2203 /// assert_eq!(6, vec.capacity());
2204 /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
2205 /// ```
2206 ///
2207 /// The returned mutable reference can be used to continue the call chain:
2208 ///
2209 /// ```
2210 /// #![feature(iter_collect_into)]
2211 ///
2212 /// let a = [1, 2, 3];
2213 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2214 ///
2215 /// let count = a.iter().collect_into(&mut vec).iter().count();
2216 ///
2217 /// assert_eq!(count, vec.len());
2218 /// assert_eq!(vec, vec![1, 2, 3]);
2219 ///
2220 /// let count = a.iter().collect_into(&mut vec).iter().count();
2221 ///
2222 /// assert_eq!(count, vec.len());
2223 /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
2224 /// ```
2225 #[inline]
2226 #[unstable(feature = "iter_collect_into", issue = "94780")]
2227 #[rustc_non_const_trait_method]
2228 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2229 where
2230 Self: Sized,
2231 {
2232 collection.extend(self);
2233 collection
2234 }
2235
2236 /// Consumes an iterator, creating two collections from it.
2237 ///
2238 /// The predicate passed to `partition()` can return `true`, or `false`.
2239 /// `partition()` returns a pair, all of the elements for which it returned
2240 /// `true`, and all of the elements for which it returned `false`.
2241 ///
2242 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2243 ///
2244 /// [`is_partitioned()`]: Iterator::is_partitioned
2245 /// [`partition_in_place()`]: Iterator::partition_in_place
2246 ///
2247 /// # Examples
2248 ///
2249 /// ```
2250 /// let a = [1, 2, 3];
2251 ///
2252 /// let (even, odd): (Vec<_>, Vec<_>) = a
2253 /// .into_iter()
2254 /// .partition(|n| n % 2 == 0);
2255 ///
2256 /// assert_eq!(even, [2]);
2257 /// assert_eq!(odd, [1, 3]);
2258 /// ```
2259 #[stable(feature = "rust1", since = "1.0.0")]
2260 #[rustc_non_const_trait_method]
2261 fn partition<B, F>(self, f: F) -> (B, B)
2262 where
2263 Self: Sized,
2264 B: Default + Extend<Self::Item>,
2265 F: FnMut(&Self::Item) -> bool,
2266 {
2267 #[inline]
2268 fn extend<'a, T, B: Extend<T>>(
2269 mut f: impl FnMut(&T) -> bool + 'a,
2270 left: &'a mut B,
2271 right: &'a mut B,
2272 ) -> impl FnMut((), T) + 'a {
2273 move |(), x| {
2274 if f(&x) {
2275 left.extend_one(x);
2276 } else {
2277 right.extend_one(x);
2278 }
2279 }
2280 }
2281
2282 let mut left: B = Default::default();
2283 let mut right: B = Default::default();
2284
2285 self.fold((), extend(f, &mut left, &mut right));
2286
2287 (left, right)
2288 }
2289
2290 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2291 /// such that all those that return `true` precede all those that return `false`.
2292 /// Returns the number of `true` elements found.
2293 ///
2294 /// The relative order of partitioned items is not maintained.
2295 ///
2296 /// # Current implementation
2297 ///
2298 /// The current algorithm tries to find the first element for which the predicate evaluates
2299 /// to false and the last element for which it evaluates to true, and repeatedly swaps them.
2300 ///
2301 /// Time complexity: *O*(*n*)
2302 ///
2303 /// See also [`is_partitioned()`] and [`partition()`].
2304 ///
2305 /// [`is_partitioned()`]: Iterator::is_partitioned
2306 /// [`partition()`]: Iterator::partition
2307 ///
2308 /// # Examples
2309 ///
2310 /// ```
2311 /// #![feature(iter_partition_in_place)]
2312 ///
2313 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2314 ///
2315 /// // Partition in-place between evens and odds
2316 /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);
2317 ///
2318 /// assert_eq!(i, 3);
2319 /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens
2320 /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds
2321 /// ```
2322 #[unstable(feature = "iter_partition_in_place", issue = "62543")]
2323 #[rustc_non_const_trait_method]
2324 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2325 where
2326 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2327 P: FnMut(&T) -> bool,
2328 {
2329 // FIXME: should we worry about the count overflowing? The only way to have more than
2330 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2331
2332 // These closure "factory" functions exist to avoid genericity in `Self`.
2333
2334 #[inline]
2335 fn is_false<'a, T>(
2336 predicate: &'a mut impl FnMut(&T) -> bool,
2337 true_count: &'a mut usize,
2338 ) -> impl FnMut(&&mut T) -> bool + 'a {
2339 move |x| {
2340 let p = predicate(&**x);
2341 *true_count += p as usize;
2342 !p
2343 }
2344 }
2345
2346 #[inline]
2347 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2348 move |x| predicate(&**x)
2349 }
2350
2351 // Repeatedly find the first `false` and swap it with the last `true`.
2352 let mut true_count = 0;
2353 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2354 if let Some(tail) = self.rfind(is_true(predicate)) {
2355 crate::mem::swap(head, tail);
2356 true_count += 1;
2357 } else {
2358 break;
2359 }
2360 }
2361 true_count
2362 }
2363
2364 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2365 /// such that all those that return `true` precede all those that return `false`.
2366 ///
2367 /// See also [`partition()`] and [`partition_in_place()`].
2368 ///
2369 /// [`partition()`]: Iterator::partition
2370 /// [`partition_in_place()`]: Iterator::partition_in_place
2371 ///
2372 /// # Examples
2373 ///
2374 /// ```
2375 /// #![feature(iter_is_partitioned)]
2376 ///
2377 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2378 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2379 /// ```
2380 #[unstable(feature = "iter_is_partitioned", issue = "62544")]
2381 #[rustc_non_const_trait_method]
2382 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2383 where
2384 Self: Sized,
2385 P: FnMut(Self::Item) -> bool,
2386 {
2387 // Either all items test `true`, or the first clause stops at `false`
2388 // and we check that there are no more `true` items after that.
2389 self.all(&mut predicate) || !self.any(predicate)
2390 }
2391
2392 /// An iterator method that applies a function as long as it returns
2393 /// successfully, producing a single, final value.
2394 ///
2395 /// `try_fold()` takes two arguments: an initial value, and a closure with
2396 /// two arguments: an 'accumulator', and an element. The closure either
2397 /// returns successfully, with the value that the accumulator should have
2398 /// for the next iteration, or it returns failure, with an error value that
2399 /// is propagated back to the caller immediately (short-circuiting).
2400 ///
2401 /// The initial value is the value the accumulator will have on the first
2402 /// call. If applying the closure succeeded against every element of the
2403 /// iterator, `try_fold()` returns the final accumulator as success.
2404 ///
2405 /// Folding is useful whenever you have a collection of something, and want
2406 /// to produce a single value from it.
2407 ///
2408 /// # Note to Implementors
2409 ///
2410 /// Several of the other (forward) methods have default implementations in
2411 /// terms of this one, so try to implement this explicitly if it can
2412 /// do something better than the default `for` loop implementation.
2413 ///
2414 /// In particular, try to have this call `try_fold()` on the internal parts
2415 /// from which this iterator is composed. If multiple calls are needed,
2416 /// the `?` operator may be convenient for chaining the accumulator value
2417 /// along, but beware any invariants that need to be upheld before those
2418 /// early returns. This is a `&mut self` method, so iteration needs to be
2419 /// resumable after hitting an error here.
2420 ///
2421 /// # Examples
2422 ///
2423 /// Basic usage:
2424 ///
2425 /// ```
2426 /// let a = [1, 2, 3];
2427 ///
2428 /// // the checked sum of all of the elements of the array
2429 /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));
2430 ///
2431 /// assert_eq!(sum, Some(6));
2432 /// ```
2433 ///
2434 /// Short-circuiting:
2435 ///
2436 /// ```
2437 /// let a = [10, 20, 30, 100, 40, 50];
2438 /// let mut iter = a.into_iter();
2439 ///
2440 /// // This sum overflows when adding the 100 element
2441 /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
2442 /// assert_eq!(sum, None);
2443 ///
2444 /// // Because it short-circuited, the remaining elements are still
2445 /// // available through the iterator.
2446 /// assert_eq!(iter.len(), 2);
2447 /// assert_eq!(iter.next(), Some(40));
2448 /// ```
2449 ///
2450 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2451 /// a similar idea:
2452 ///
2453 /// ```
2454 /// use std::ops::ControlFlow;
2455 ///
2456 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2457 /// if let Some(next) = prev.checked_add(x) {
2458 /// ControlFlow::Continue(next)
2459 /// } else {
2460 /// ControlFlow::Break(prev)
2461 /// }
2462 /// });
2463 /// assert_eq!(triangular, ControlFlow::Break(120));
2464 ///
2465 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2466 /// if let Some(next) = prev.checked_add(x) {
2467 /// ControlFlow::Continue(next)
2468 /// } else {
2469 /// ControlFlow::Break(prev)
2470 /// }
2471 /// });
2472 /// assert_eq!(triangular, ControlFlow::Continue(435));
2473 /// ```
2474 #[inline]
2475 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2476 #[rustc_non_const_trait_method]
2477 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2478 where
2479 Self: Sized,
2480 F: FnMut(B, Self::Item) -> R,
2481 R: Try<Output = B>,
2482 {
2483 let mut accum = init;
2484 while let Some(x) = self.next() {
2485 accum = f(accum, x)?;
2486 }
2487 try { accum }
2488 }
2489
2490 /// An iterator method that applies a fallible function to each item in the
2491 /// iterator, stopping at the first error and returning that error.
2492 ///
2493 /// This can also be thought of as the fallible form of [`for_each()`]
2494 /// or as the stateless version of [`try_fold()`].
2495 ///
2496 /// [`for_each()`]: Iterator::for_each
2497 /// [`try_fold()`]: Iterator::try_fold
2498 ///
2499 /// # Examples
2500 ///
2501 /// ```
2502 /// use std::fs::rename;
2503 /// use std::io::{stdout, Write};
2504 /// use std::path::Path;
2505 ///
2506 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2507 ///
2508 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2509 /// assert!(res.is_ok());
2510 ///
2511 /// let mut it = data.iter().cloned();
2512 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2513 /// assert!(res.is_err());
2514 /// // It short-circuited, so the remaining items are still in the iterator:
2515 /// assert_eq!(it.next(), Some("stale_bread.json"));
2516 /// ```
2517 ///
2518 /// The [`ControlFlow`] type can be used with this method for the situations
2519 /// in which you'd use `break` and `continue` in a normal loop:
2520 ///
2521 /// ```
2522 /// use std::ops::ControlFlow;
2523 ///
2524 /// let r = (2..100).try_for_each(|x| {
2525 /// if 323 % x == 0 {
2526 /// return ControlFlow::Break(x)
2527 /// }
2528 ///
2529 /// ControlFlow::Continue(())
2530 /// });
2531 /// assert_eq!(r, ControlFlow::Break(17));
2532 /// ```
2533 #[inline]
2534 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2535 #[rustc_non_const_trait_method]
2536 fn try_for_each<F, R>(&mut self, f: F) -> R
2537 where
2538 Self: Sized,
2539 F: FnMut(Self::Item) -> R,
2540 R: Try<Output = ()>,
2541 {
2542 #[inline]
2543 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2544 move |(), x| f(x)
2545 }
2546
2547 self.try_fold((), call(f))
2548 }
2549
2550 /// Folds every element into an accumulator by applying an operation,
2551 /// returning the final result.
2552 ///
2553 /// `fold()` takes two arguments: an initial value, and a closure with two
2554 /// arguments: an 'accumulator', and an element. The closure returns the value that
2555 /// the accumulator should have for the next iteration.
2556 ///
2557 /// The initial value is the value the accumulator will have on the first
2558 /// call.
2559 ///
2560 /// After applying this closure to every element of the iterator, `fold()`
2561 /// returns the accumulator.
2562 ///
2563 /// This operation is sometimes called 'reduce' or 'inject'.
2564 ///
2565 /// Folding is useful whenever you have a collection of something, and want
2566 /// to produce a single value from it.
2567 ///
2568 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2569 /// might not terminate for infinite iterators, even on traits for which a
2570 /// result is determinable in finite time.
2571 ///
2572 /// Note: [`reduce()`] can be used to use the first element as the initial
2573 /// value, if the accumulator type and item type is the same.
2574 ///
2575 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2576 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2577 /// operators like `-` the order will affect the final result.
2578 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2579 ///
2580 /// # Note to Implementors
2581 ///
2582 /// Several of the other (forward) methods have default implementations in
2583 /// terms of this one, so try to implement this explicitly if it can
2584 /// do something better than the default `for` loop implementation.
2585 ///
2586 /// In particular, try to have this call `fold()` on the internal parts
2587 /// from which this iterator is composed.
2588 ///
2589 /// # Examples
2590 ///
2591 /// Basic usage:
2592 ///
2593 /// ```
2594 /// let a = [1, 2, 3];
2595 ///
2596 /// // the sum of all of the elements of the array
2597 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2598 ///
2599 /// assert_eq!(sum, 6);
2600 /// ```
2601 ///
2602 /// Let's walk through each step of the iteration here:
2603 ///
2604 /// | element | acc | x | result |
2605 /// |---------|-----|---|--------|
2606 /// | | 0 | | |
2607 /// | 1 | 0 | 1 | 1 |
2608 /// | 2 | 1 | 2 | 3 |
2609 /// | 3 | 3 | 3 | 6 |
2610 ///
2611 /// And so, our final result, `6`.
2612 ///
2613 /// This example demonstrates the left-associative nature of `fold()`:
2614 /// it builds a string, starting with an initial value
2615 /// and continuing with each element from the front until the back:
2616 ///
2617 /// ```
2618 /// let numbers = [1, 2, 3, 4, 5];
2619 ///
2620 /// let zero = "0".to_string();
2621 ///
2622 /// let result = numbers.iter().fold(zero, |acc, &x| {
2623 /// format!("({acc} + {x})")
2624 /// });
2625 ///
2626 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2627 /// ```
2628 /// It's common for people who haven't used iterators a lot to
2629 /// use a `for` loop with a list of things to build up a result. Those
2630 /// can be turned into `fold()`s:
2631 ///
2632 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2633 ///
2634 /// ```
2635 /// let numbers = [1, 2, 3, 4, 5];
2636 ///
2637 /// let mut result = 0;
2638 ///
2639 /// // for loop:
2640 /// for i in &numbers {
2641 /// result = result + i;
2642 /// }
2643 ///
2644 /// // fold:
2645 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2646 ///
2647 /// // they're the same
2648 /// assert_eq!(result, result2);
2649 /// ```
2650 ///
2651 /// [`reduce()`]: Iterator::reduce
2652 #[doc(alias = "inject", alias = "foldl")]
2653 #[inline]
2654 #[stable(feature = "rust1", since = "1.0.0")]
2655 #[rustc_non_const_trait_method]
2656 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2657 where
2658 Self: Sized,
2659 F: FnMut(B, Self::Item) -> B,
2660 {
2661 let mut accum = init;
2662 while let Some(x) = self.next() {
2663 accum = f(accum, x);
2664 }
2665 accum
2666 }
2667
2668 /// Reduces the elements to a single one, by repeatedly applying a reducing
2669 /// operation.
2670 ///
2671 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2672 /// result of the reduction.
2673 ///
2674 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2675 /// For iterators with at least one element, this is the same as [`fold()`]
2676 /// with the first element of the iterator as the initial accumulator value, folding
2677 /// every subsequent element into it.
2678 ///
2679 /// [`fold()`]: Iterator::fold
2680 ///
2681 /// # Example
2682 ///
2683 /// ```
2684 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
2685 /// assert_eq!(reduced, 45);
2686 ///
2687 /// // Which is equivalent to doing it with `fold`:
2688 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2689 /// assert_eq!(reduced, folded);
2690 /// ```
2691 #[inline]
2692 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2693 #[rustc_non_const_trait_method]
2694 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2695 where
2696 Self: Sized,
2697 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2698 {
2699 let first = self.next()?;
2700 Some(self.fold(first, f))
2701 }
2702
2703 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2704 /// closure returns a failure, the failure is propagated back to the caller immediately.
2705 ///
2706 /// The return type of this method depends on the return type of the closure. If the closure
2707 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2708 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2709 /// `Option<Option<Self::Item>>`.
2710 ///
2711 /// When called on an empty iterator, this function will return either `Some(None)` or
2712 /// `Ok(None)` depending on the type of the provided closure.
2713 ///
2714 /// For iterators with at least one element, this is essentially the same as calling
2715 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2716 ///
2717 /// [`try_fold()`]: Iterator::try_fold
2718 ///
2719 /// # Examples
2720 ///
2721 /// Safely calculate the sum of a series of numbers:
2722 ///
2723 /// ```
2724 /// #![feature(iterator_try_reduce)]
2725 ///
2726 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2727 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2728 /// assert_eq!(sum, Some(Some(58)));
2729 /// ```
2730 ///
2731 /// Determine when a reduction short circuited:
2732 ///
2733 /// ```
2734 /// #![feature(iterator_try_reduce)]
2735 ///
2736 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2737 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2738 /// assert_eq!(sum, None);
2739 /// ```
2740 ///
2741 /// Determine when a reduction was not performed because there are no elements:
2742 ///
2743 /// ```
2744 /// #![feature(iterator_try_reduce)]
2745 ///
2746 /// let numbers: Vec<usize> = Vec::new();
2747 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2748 /// assert_eq!(sum, Some(None));
2749 /// ```
2750 ///
2751 /// Use a [`Result`] instead of an [`Option`]:
2752 ///
2753 /// ```
2754 /// #![feature(iterator_try_reduce)]
2755 ///
2756 /// let numbers = vec!["1", "2", "3", "4", "5"];
2757 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2758 /// numbers.into_iter().try_reduce(|x, y| {
2759 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2760 /// });
2761 /// assert_eq!(max, Ok(Some("5")));
2762 /// ```
2763 #[inline]
2764 #[unstable(feature = "iterator_try_reduce", issue = "87053")]
2765 #[rustc_non_const_trait_method]
2766 fn try_reduce<R>(
2767 &mut self,
2768 f: impl FnMut(Self::Item, Self::Item) -> R,
2769 ) -> ChangeOutputType<R, Option<R::Output>>
2770 where
2771 Self: Sized,
2772 R: Try<Output = Self::Item, Residual: Residual<Option<Self::Item>>>,
2773 {
2774 let first = match self.next() {
2775 Some(i) => i,
2776 None => return Try::from_output(None),
2777 };
2778
2779 match self.try_fold(first, f).branch() {
2780 ControlFlow::Break(r) => FromResidual::from_residual(r),
2781 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2782 }
2783 }
2784
2785 /// Tests if every element of the iterator matches a predicate.
2786 ///
2787 /// `all()` takes a closure that returns `true` or `false`. It applies
2788 /// this closure to each element of the iterator, and if they all return
2789 /// `true`, then so does `all()`. If any of them return `false`, it
2790 /// returns `false`.
2791 ///
2792 /// `all()` is short-circuiting; in other words, it will stop processing
2793 /// as soon as it finds a `false`, given that no matter what else happens,
2794 /// the result will also be `false`.
2795 ///
2796 /// An empty iterator returns `true`.
2797 ///
2798 /// # Examples
2799 ///
2800 /// Basic usage:
2801 ///
2802 /// ```
2803 /// let a = [1, 2, 3];
2804 ///
2805 /// assert!(a.into_iter().all(|x| x > 0));
2806 ///
2807 /// assert!(!a.into_iter().all(|x| x > 2));
2808 /// ```
2809 ///
2810 /// Stopping at the first `false`:
2811 ///
2812 /// ```
2813 /// let a = [1, 2, 3];
2814 ///
2815 /// let mut iter = a.into_iter();
2816 ///
2817 /// assert!(!iter.all(|x| x != 2));
2818 ///
2819 /// // we can still use `iter`, as there are more elements.
2820 /// assert_eq!(iter.next(), Some(3));
2821 /// ```
2822 #[inline]
2823 #[stable(feature = "rust1", since = "1.0.0")]
2824 #[rustc_non_const_trait_method]
2825 fn all<F>(&mut self, f: F) -> bool
2826 where
2827 Self: Sized,
2828 F: FnMut(Self::Item) -> bool,
2829 {
2830 #[inline]
2831 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2832 move |(), x| {
2833 if f(x) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
2834 }
2835 }
2836 self.try_fold((), check(f)) == ControlFlow::Continue(())
2837 }
2838
2839 /// Tests if any element of the iterator matches a predicate.
2840 ///
2841 /// `any()` takes a closure that returns `true` or `false`. It applies
2842 /// this closure to each element of the iterator, and if any of them return
2843 /// `true`, then so does `any()`. If they all return `false`, it
2844 /// returns `false`.
2845 ///
2846 /// `any()` is short-circuiting; in other words, it will stop processing
2847 /// as soon as it finds a `true`, given that no matter what else happens,
2848 /// the result will also be `true`.
2849 ///
2850 /// An empty iterator returns `false`.
2851 ///
2852 /// # Examples
2853 ///
2854 /// Basic usage:
2855 ///
2856 /// ```
2857 /// let a = [1, 2, 3];
2858 ///
2859 /// assert!(a.into_iter().any(|x| x > 0));
2860 ///
2861 /// assert!(!a.into_iter().any(|x| x > 5));
2862 /// ```
2863 ///
2864 /// Stopping at the first `true`:
2865 ///
2866 /// ```
2867 /// let a = [1, 2, 3];
2868 ///
2869 /// let mut iter = a.into_iter();
2870 ///
2871 /// assert!(iter.any(|x| x != 2));
2872 ///
2873 /// // we can still use `iter`, as there are more elements.
2874 /// assert_eq!(iter.next(), Some(2));
2875 /// ```
2876 #[inline]
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 #[rustc_non_const_trait_method]
2879 fn any<F>(&mut self, f: F) -> bool
2880 where
2881 Self: Sized,
2882 F: FnMut(Self::Item) -> bool,
2883 {
2884 #[inline]
2885 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2886 move |(), x| {
2887 if f(x) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2888 }
2889 }
2890
2891 self.try_fold((), check(f)) == ControlFlow::Break(())
2892 }
2893
2894 /// Searches for an element of an iterator that satisfies a predicate.
2895 ///
2896 /// `find()` takes a closure that returns `true` or `false`. It applies
2897 /// this closure to each element of the iterator, and if any of them return
2898 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2899 /// `false`, it returns [`None`].
2900 ///
2901 /// `find()` is short-circuiting; in other words, it will stop processing
2902 /// as soon as the closure returns `true`.
2903 ///
2904 /// Because `find()` takes a reference, and many iterators iterate over
2905 /// references, this leads to a possibly confusing situation where the
2906 /// argument is a double reference. You can see this effect in the
2907 /// examples below, with `&&x`.
2908 ///
2909 /// If you need the index of the element, see [`position()`].
2910 ///
2911 /// [`Some(element)`]: Some
2912 /// [`position()`]: Iterator::position
2913 ///
2914 /// # Examples
2915 ///
2916 /// Basic usage:
2917 ///
2918 /// ```
2919 /// let a = [1, 2, 3];
2920 ///
2921 /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
2922 /// assert_eq!(a.into_iter().find(|&x| x == 5), None);
2923 /// ```
2924 ///
2925 /// Iterating over references:
2926 ///
2927 /// ```
2928 /// let a = [1, 2, 3];
2929 ///
2930 /// // `iter()` yields references i.e. `&i32` and `find()` takes a
2931 /// // reference to each element.
2932 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2933 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2934 /// ```
2935 ///
2936 /// Stopping at the first `true`:
2937 ///
2938 /// ```
2939 /// let a = [1, 2, 3];
2940 ///
2941 /// let mut iter = a.into_iter();
2942 ///
2943 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2944 ///
2945 /// // we can still use `iter`, as there are more elements.
2946 /// assert_eq!(iter.next(), Some(3));
2947 /// ```
2948 ///
2949 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2950 #[inline]
2951 #[stable(feature = "rust1", since = "1.0.0")]
2952 #[rustc_non_const_trait_method]
2953 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2954 where
2955 Self: Sized,
2956 P: FnMut(&Self::Item) -> bool,
2957 {
2958 #[inline]
2959 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2960 move |(), x| {
2961 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2962 }
2963 }
2964
2965 self.try_fold((), check(predicate)).break_value()
2966 }
2967
2968 /// Applies function to the elements of iterator and returns
2969 /// the first non-none result.
2970 ///
2971 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2972 ///
2973 /// # Examples
2974 ///
2975 /// ```
2976 /// let a = ["lol", "NaN", "2", "5"];
2977 ///
2978 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2979 ///
2980 /// assert_eq!(first_number, Some(2));
2981 /// ```
2982 #[inline]
2983 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2984 #[rustc_non_const_trait_method]
2985 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2986 where
2987 Self: Sized,
2988 F: FnMut(Self::Item) -> Option<B>,
2989 {
2990 #[inline]
2991 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2992 move |(), x| match f(x) {
2993 Some(x) => ControlFlow::Break(x),
2994 None => ControlFlow::Continue(()),
2995 }
2996 }
2997
2998 self.try_fold((), check(f)).break_value()
2999 }
3000
3001 /// Applies function to the elements of iterator and returns
3002 /// the first true result or the first error.
3003 ///
3004 /// The return type of this method depends on the return type of the closure.
3005 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
3006 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
3007 ///
3008 /// # Examples
3009 ///
3010 /// ```
3011 /// #![feature(try_find)]
3012 ///
3013 /// let a = ["1", "2", "lol", "NaN", "5"];
3014 ///
3015 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
3016 /// Ok(s.parse::<i32>()? == search)
3017 /// };
3018 ///
3019 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
3020 /// assert_eq!(result, Ok(Some("2")));
3021 ///
3022 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
3023 /// assert!(result.is_err());
3024 /// ```
3025 ///
3026 /// This also supports other types which implement [`Try`], not just [`Result`].
3027 ///
3028 /// ```
3029 /// #![feature(try_find)]
3030 ///
3031 /// use std::num::NonZero;
3032 ///
3033 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
3034 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3035 /// assert_eq!(result, Some(Some(4)));
3036 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3037 /// assert_eq!(result, Some(None));
3038 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3039 /// assert_eq!(result, None);
3040 /// ```
3041 #[inline]
3042 #[unstable(feature = "try_find", issue = "63178")]
3043 #[rustc_non_const_trait_method]
3044 fn try_find<R>(
3045 &mut self,
3046 f: impl FnMut(&Self::Item) -> R,
3047 ) -> ChangeOutputType<R, Option<Self::Item>>
3048 where
3049 Self: Sized,
3050 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
3051 {
3052 #[inline]
3053 fn check<I, V, R>(
3054 mut f: impl FnMut(&I) -> V,
3055 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
3056 where
3057 V: Try<Output = bool, Residual = R>,
3058 R: Residual<Option<I>>,
3059 {
3060 move |(), x| match f(&x).branch() {
3061 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3062 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3063 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3064 }
3065 }
3066
3067 match self.try_fold((), check(f)) {
3068 ControlFlow::Break(x) => x,
3069 ControlFlow::Continue(()) => Try::from_output(None),
3070 }
3071 }
3072
3073 /// Searches for an element in an iterator, returning its index.
3074 ///
3075 /// `position()` takes a closure that returns `true` or `false`. It applies
3076 /// this closure to each element of the iterator, and if one of them
3077 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3078 /// them return `false`, it returns [`None`].
3079 ///
3080 /// `position()` is short-circuiting; in other words, it will stop
3081 /// processing as soon as it finds a `true`.
3082 ///
3083 /// # Overflow Behavior
3084 ///
3085 /// The method does no guarding against overflows, so if there are more
3086 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3087 /// result or panics. If overflow checks are enabled, a panic is
3088 /// guaranteed.
3089 ///
3090 /// # Panics
3091 ///
3092 /// This function might panic if the iterator has more than `usize::MAX`
3093 /// non-matching elements.
3094 ///
3095 /// [`Some(index)`]: Some
3096 ///
3097 /// # Examples
3098 ///
3099 /// Basic usage:
3100 ///
3101 /// ```
3102 /// let a = [1, 2, 3];
3103 ///
3104 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3105 ///
3106 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3107 /// ```
3108 ///
3109 /// Stopping at the first `true`:
3110 ///
3111 /// ```
3112 /// let a = [1, 2, 3, 4];
3113 ///
3114 /// let mut iter = a.into_iter();
3115 ///
3116 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3117 ///
3118 /// // we can still use `iter`, as there are more elements.
3119 /// assert_eq!(iter.next(), Some(3));
3120 ///
3121 /// // The returned index depends on iterator state
3122 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3123 ///
3124 /// ```
3125 #[inline]
3126 #[stable(feature = "rust1", since = "1.0.0")]
3127 #[rustc_non_const_trait_method]
3128 fn position<P>(&mut self, predicate: P) -> Option<usize>
3129 where
3130 Self: Sized,
3131 P: FnMut(Self::Item) -> bool,
3132 {
3133 #[inline]
3134 fn check<'a, T>(
3135 mut predicate: impl FnMut(T) -> bool + 'a,
3136 acc: &'a mut usize,
3137 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3138 #[rustc_inherit_overflow_checks]
3139 move |_, x| {
3140 if predicate(x) {
3141 ControlFlow::Break(*acc)
3142 } else {
3143 *acc += 1;
3144 ControlFlow::Continue(())
3145 }
3146 }
3147 }
3148
3149 let mut acc = 0;
3150 self.try_fold((), check(predicate, &mut acc)).break_value()
3151 }
3152
3153 /// Searches for an element in an iterator from the right, returning its
3154 /// index.
3155 ///
3156 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3157 /// this closure to each element of the iterator, starting from the end,
3158 /// and if one of them returns `true`, then `rposition()` returns
3159 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3160 ///
3161 /// `rposition()` is short-circuiting; in other words, it will stop
3162 /// processing as soon as it finds a `true`.
3163 ///
3164 /// [`Some(index)`]: Some
3165 ///
3166 /// # Examples
3167 ///
3168 /// Basic usage:
3169 ///
3170 /// ```
3171 /// let a = [1, 2, 3];
3172 ///
3173 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3174 ///
3175 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3176 /// ```
3177 ///
3178 /// Stopping at the first `true`:
3179 ///
3180 /// ```
3181 /// let a = [-1, 2, 3, 4];
3182 ///
3183 /// let mut iter = a.into_iter();
3184 ///
3185 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3186 ///
3187 /// // we can still use `iter`, as there are more elements.
3188 /// assert_eq!(iter.next(), Some(-1));
3189 /// assert_eq!(iter.next_back(), Some(3));
3190 /// ```
3191 #[inline]
3192 #[stable(feature = "rust1", since = "1.0.0")]
3193 #[rustc_non_const_trait_method]
3194 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3195 where
3196 P: FnMut(Self::Item) -> bool,
3197 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3198 {
3199 // No need for an overflow check here, because `ExactSizeIterator`
3200 // implies that the number of elements fits into a `usize`.
3201 #[inline]
3202 fn check<T>(
3203 mut predicate: impl FnMut(T) -> bool,
3204 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3205 move |i, x| {
3206 let i = i - 1;
3207 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3208 }
3209 }
3210
3211 let n = self.len();
3212 self.try_rfold(n, check(predicate)).break_value()
3213 }
3214
3215 /// Returns the maximum element of an iterator.
3216 ///
3217 /// If several elements are equally maximum, the last element is
3218 /// returned. If the iterator is empty, [`None`] is returned.
3219 ///
3220 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3221 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3222 /// ```
3223 /// assert_eq!(
3224 /// [2.4, f32::NAN, 1.3]
3225 /// .into_iter()
3226 /// .reduce(f32::max)
3227 /// .unwrap_or(0.),
3228 /// 2.4
3229 /// );
3230 /// ```
3231 ///
3232 /// # Examples
3233 ///
3234 /// ```
3235 /// let a = [1, 2, 3];
3236 /// let b: [u32; 0] = [];
3237 ///
3238 /// assert_eq!(a.into_iter().max(), Some(3));
3239 /// assert_eq!(b.into_iter().max(), None);
3240 /// ```
3241 #[inline]
3242 #[stable(feature = "rust1", since = "1.0.0")]
3243 #[rustc_non_const_trait_method]
3244 fn max(self) -> Option<Self::Item>
3245 where
3246 Self: Sized,
3247 Self::Item: Ord,
3248 {
3249 self.max_by(Ord::cmp)
3250 }
3251
3252 /// Returns the minimum element of an iterator.
3253 ///
3254 /// If several elements are equally minimum, the first element is returned.
3255 /// If the iterator is empty, [`None`] is returned.
3256 ///
3257 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3258 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3259 /// ```
3260 /// assert_eq!(
3261 /// [2.4, f32::NAN, 1.3]
3262 /// .into_iter()
3263 /// .reduce(f32::min)
3264 /// .unwrap_or(0.),
3265 /// 1.3
3266 /// );
3267 /// ```
3268 ///
3269 /// # Examples
3270 ///
3271 /// ```
3272 /// let a = [1, 2, 3];
3273 /// let b: [u32; 0] = [];
3274 ///
3275 /// assert_eq!(a.into_iter().min(), Some(1));
3276 /// assert_eq!(b.into_iter().min(), None);
3277 /// ```
3278 #[inline]
3279 #[stable(feature = "rust1", since = "1.0.0")]
3280 #[rustc_non_const_trait_method]
3281 fn min(self) -> Option<Self::Item>
3282 where
3283 Self: Sized,
3284 Self::Item: Ord,
3285 {
3286 self.min_by(Ord::cmp)
3287 }
3288
3289 /// Returns the element that gives the maximum value from the
3290 /// specified function.
3291 ///
3292 /// If several elements are equally maximum, the last element is
3293 /// returned. If the iterator is empty, [`None`] is returned.
3294 ///
3295 /// # Examples
3296 ///
3297 /// ```
3298 /// let a = [-3_i32, 0, 1, 5, -10];
3299 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3300 /// ```
3301 #[inline]
3302 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3303 #[rustc_non_const_trait_method]
3304 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3305 where
3306 Self: Sized,
3307 F: FnMut(&Self::Item) -> B,
3308 {
3309 #[inline]
3310 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3311 move |x| (f(&x), x)
3312 }
3313
3314 #[inline]
3315 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3316 x_p.cmp(y_p)
3317 }
3318
3319 let (_, x) = self.map(key(f)).max_by(compare)?;
3320 Some(x)
3321 }
3322
3323 /// Returns the element that gives the maximum value with respect to the
3324 /// specified comparison function.
3325 ///
3326 /// If several elements are equally maximum, the last element is
3327 /// returned. If the iterator is empty, [`None`] is returned.
3328 ///
3329 /// # Examples
3330 ///
3331 /// ```
3332 /// let a = [-3_i32, 0, 1, 5, -10];
3333 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3334 /// ```
3335 #[inline]
3336 #[stable(feature = "iter_max_by", since = "1.15.0")]
3337 #[rustc_non_const_trait_method]
3338 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3339 where
3340 Self: Sized,
3341 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3342 {
3343 #[inline]
3344 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3345 move |x, y| cmp::max_by(x, y, &mut compare)
3346 }
3347
3348 self.reduce(fold(compare))
3349 }
3350
3351 /// Returns the element that gives the minimum value from the
3352 /// specified function.
3353 ///
3354 /// If several elements are equally minimum, the first element is
3355 /// returned. If the iterator is empty, [`None`] is returned.
3356 ///
3357 /// # Examples
3358 ///
3359 /// ```
3360 /// let a = [-3_i32, 0, 1, 5, -10];
3361 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3362 /// ```
3363 #[inline]
3364 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3365 #[rustc_non_const_trait_method]
3366 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3367 where
3368 Self: Sized,
3369 F: FnMut(&Self::Item) -> B,
3370 {
3371 #[inline]
3372 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3373 move |x| (f(&x), x)
3374 }
3375
3376 #[inline]
3377 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3378 x_p.cmp(y_p)
3379 }
3380
3381 let (_, x) = self.map(key(f)).min_by(compare)?;
3382 Some(x)
3383 }
3384
3385 /// Returns the element that gives the minimum value with respect to the
3386 /// specified comparison function.
3387 ///
3388 /// If several elements are equally minimum, the first element is
3389 /// returned. If the iterator is empty, [`None`] is returned.
3390 ///
3391 /// # Examples
3392 ///
3393 /// ```
3394 /// let a = [-3_i32, 0, 1, 5, -10];
3395 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3396 /// ```
3397 #[inline]
3398 #[stable(feature = "iter_min_by", since = "1.15.0")]
3399 #[rustc_non_const_trait_method]
3400 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3401 where
3402 Self: Sized,
3403 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3404 {
3405 #[inline]
3406 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3407 move |x, y| cmp::min_by(x, y, &mut compare)
3408 }
3409
3410 self.reduce(fold(compare))
3411 }
3412
3413 /// Reverses an iterator's direction.
3414 ///
3415 /// Usually, iterators iterate from left to right. After using `rev()`,
3416 /// an iterator will instead iterate from right to left.
3417 ///
3418 /// This is only possible if the iterator has an end, so `rev()` only
3419 /// works on [`DoubleEndedIterator`]s.
3420 ///
3421 /// # Examples
3422 ///
3423 /// ```
3424 /// let a = [1, 2, 3];
3425 ///
3426 /// let mut iter = a.into_iter().rev();
3427 ///
3428 /// assert_eq!(iter.next(), Some(3));
3429 /// assert_eq!(iter.next(), Some(2));
3430 /// assert_eq!(iter.next(), Some(1));
3431 ///
3432 /// assert_eq!(iter.next(), None);
3433 /// ```
3434 #[inline]
3435 #[doc(alias = "reverse")]
3436 #[stable(feature = "rust1", since = "1.0.0")]
3437 #[rustc_non_const_trait_method]
3438 fn rev(self) -> Rev<Self>
3439 where
3440 Self: Sized + DoubleEndedIterator,
3441 {
3442 Rev::new(self)
3443 }
3444
3445 /// Converts an iterator of pairs into a pair of containers.
3446 ///
3447 /// `unzip()` consumes an entire iterator of pairs, producing two
3448 /// collections: one from the left elements of the pairs, and one
3449 /// from the right elements.
3450 ///
3451 /// This function is, in some sense, the opposite of [`zip`].
3452 ///
3453 /// [`zip`]: Iterator::zip
3454 ///
3455 /// # Examples
3456 ///
3457 /// ```
3458 /// let a = [(1, 2), (3, 4), (5, 6)];
3459 ///
3460 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3461 ///
3462 /// assert_eq!(left, [1, 3, 5]);
3463 /// assert_eq!(right, [2, 4, 6]);
3464 ///
3465 /// // you can also unzip multiple nested tuples at once
3466 /// let a = [(1, (2, 3)), (4, (5, 6))];
3467 ///
3468 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3469 /// assert_eq!(x, [1, 4]);
3470 /// assert_eq!(y, [2, 5]);
3471 /// assert_eq!(z, [3, 6]);
3472 /// ```
3473 #[stable(feature = "rust1", since = "1.0.0")]
3474 #[rustc_non_const_trait_method]
3475 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3476 where
3477 FromA: Default + Extend<A>,
3478 FromB: Default + Extend<B>,
3479 Self: Sized + Iterator<Item = (A, B)>,
3480 {
3481 let mut unzipped: (FromA, FromB) = Default::default();
3482 unzipped.extend(self);
3483 unzipped
3484 }
3485
3486 /// Creates an iterator which copies all of its elements.
3487 ///
3488 /// This is useful when you have an iterator over `&T`, but you need an
3489 /// iterator over `T`.
3490 ///
3491 /// # Examples
3492 ///
3493 /// ```
3494 /// let a = [1, 2, 3];
3495 ///
3496 /// let v_copied: Vec<_> = a.iter().copied().collect();
3497 ///
3498 /// // copied is the same as .map(|&x| x)
3499 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3500 ///
3501 /// assert_eq!(v_copied, [1, 2, 3]);
3502 /// assert_eq!(v_map, [1, 2, 3]);
3503 /// ```
3504 #[stable(feature = "iter_copied", since = "1.36.0")]
3505 #[rustc_diagnostic_item = "iter_copied"]
3506 #[rustc_non_const_trait_method]
3507 fn copied<'a, T>(self) -> Copied<Self>
3508 where
3509 T: Copy + 'a,
3510 Self: Sized + Iterator<Item = &'a T>,
3511 {
3512 Copied::new(self)
3513 }
3514
3515 /// Creates an iterator which [`clone`]s all of its elements.
3516 ///
3517 /// This is useful when you have an iterator over `&T`, but you need an
3518 /// iterator over `T`.
3519 ///
3520 /// There is no guarantee whatsoever about the `clone` method actually
3521 /// being called *or* optimized away. So code should not depend on
3522 /// either.
3523 ///
3524 /// [`clone`]: Clone::clone
3525 ///
3526 /// # Examples
3527 ///
3528 /// Basic usage:
3529 ///
3530 /// ```
3531 /// let a = [1, 2, 3];
3532 ///
3533 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3534 ///
3535 /// // cloned is the same as .map(|&x| x), for integers
3536 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3537 ///
3538 /// assert_eq!(v_cloned, [1, 2, 3]);
3539 /// assert_eq!(v_map, [1, 2, 3]);
3540 /// ```
3541 ///
3542 /// To get the best performance, try to clone late:
3543 ///
3544 /// ```
3545 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3546 /// // don't do this:
3547 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3548 /// assert_eq!(&[vec![23]], &slower[..]);
3549 /// // instead call `cloned` late
3550 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3551 /// assert_eq!(&[vec![23]], &faster[..]);
3552 /// ```
3553 #[stable(feature = "rust1", since = "1.0.0")]
3554 #[rustc_diagnostic_item = "iter_cloned"]
3555 #[rustc_non_const_trait_method]
3556 fn cloned<'a, T>(self) -> Cloned<Self>
3557 where
3558 T: Clone + 'a,
3559 Self: Sized + Iterator<Item = &'a T>,
3560 {
3561 Cloned::new(self)
3562 }
3563
3564 /// Repeats an iterator endlessly.
3565 ///
3566 /// Instead of stopping at [`None`], the iterator will instead start again,
3567 /// from the beginning. After iterating again, it will start at the
3568 /// beginning again. And again. And again. Forever. Note that in case the
3569 /// original iterator is empty, the resulting iterator will also be empty.
3570 ///
3571 /// # Examples
3572 ///
3573 /// ```
3574 /// let a = [1, 2, 3];
3575 ///
3576 /// let mut iter = a.into_iter().cycle();
3577 ///
3578 /// loop {
3579 /// assert_eq!(iter.next(), Some(1));
3580 /// assert_eq!(iter.next(), Some(2));
3581 /// assert_eq!(iter.next(), Some(3));
3582 /// # break;
3583 /// }
3584 /// ```
3585 #[stable(feature = "rust1", since = "1.0.0")]
3586 #[inline]
3587 #[rustc_non_const_trait_method]
3588 fn cycle(self) -> Cycle<Self>
3589 where
3590 Self: Sized + Clone,
3591 {
3592 Cycle::new(self)
3593 }
3594
3595 /// Returns an iterator over `N` elements of the iterator at a time.
3596 ///
3597 /// The chunks do not overlap. If `N` does not divide the length of the
3598 /// iterator, then the last up to `N-1` elements will be omitted and can be
3599 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3600 /// function of the iterator.
3601 ///
3602 /// # Panics
3603 ///
3604 /// Panics if `N` is zero.
3605 ///
3606 /// # Examples
3607 ///
3608 /// Basic usage:
3609 ///
3610 /// ```
3611 /// #![feature(iter_array_chunks)]
3612 ///
3613 /// let mut iter = "lorem".chars().array_chunks();
3614 /// assert_eq!(iter.next(), Some(['l', 'o']));
3615 /// assert_eq!(iter.next(), Some(['r', 'e']));
3616 /// assert_eq!(iter.next(), None);
3617 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3618 /// ```
3619 ///
3620 /// ```
3621 /// #![feature(iter_array_chunks)]
3622 ///
3623 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3624 /// // ^-----^ ^------^
3625 /// for [x, y, z] in data.iter().array_chunks() {
3626 /// assert_eq!(x + y + z, 4);
3627 /// }
3628 /// ```
3629 #[track_caller]
3630 #[unstable(feature = "iter_array_chunks", issue = "100450")]
3631 #[rustc_non_const_trait_method]
3632 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3633 where
3634 Self: Sized,
3635 {
3636 ArrayChunks::new(self)
3637 }
3638
3639 /// Sums the elements of an iterator.
3640 ///
3641 /// Takes each element, adds them together, and returns the result.
3642 ///
3643 /// An empty iterator returns the *additive identity* ("zero") of the type,
3644 /// which is `0` for integers and `-0.0` for floats.
3645 ///
3646 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3647 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3648 ///
3649 /// # Panics
3650 ///
3651 /// When calling `sum()` and a primitive integer type is being returned, this
3652 /// method will panic if the computation overflows and overflow checks are
3653 /// enabled.
3654 ///
3655 /// # Examples
3656 ///
3657 /// ```
3658 /// let a = [1, 2, 3];
3659 /// let sum: i32 = a.iter().sum();
3660 ///
3661 /// assert_eq!(sum, 6);
3662 ///
3663 /// let b: Vec<f32> = vec![];
3664 /// let sum: f32 = b.iter().sum();
3665 /// assert_eq!(sum, -0.0_f32);
3666 /// ```
3667 #[stable(feature = "iter_arith", since = "1.11.0")]
3668 #[rustc_non_const_trait_method]
3669 fn sum<S>(self) -> S
3670 where
3671 Self: Sized,
3672 S: Sum<Self::Item>,
3673 {
3674 Sum::sum(self)
3675 }
3676
3677 /// Iterates over the entire iterator, multiplying all the elements
3678 ///
3679 /// An empty iterator returns the one value of the type.
3680 ///
3681 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3682 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3683 ///
3684 /// # Panics
3685 ///
3686 /// When calling `product()` and a primitive integer type is being returned,
3687 /// method will panic if the computation overflows and overflow checks are
3688 /// enabled.
3689 ///
3690 /// # Examples
3691 ///
3692 /// ```
3693 /// fn factorial(n: u32) -> u32 {
3694 /// (1..=n).product()
3695 /// }
3696 /// assert_eq!(factorial(0), 1);
3697 /// assert_eq!(factorial(1), 1);
3698 /// assert_eq!(factorial(5), 120);
3699 /// ```
3700 #[stable(feature = "iter_arith", since = "1.11.0")]
3701 #[rustc_non_const_trait_method]
3702 fn product<P>(self) -> P
3703 where
3704 Self: Sized,
3705 P: Product<Self::Item>,
3706 {
3707 Product::product(self)
3708 }
3709
3710 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3711 /// of another.
3712 ///
3713 /// # Examples
3714 ///
3715 /// ```
3716 /// use std::cmp::Ordering;
3717 ///
3718 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3719 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3720 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3721 /// ```
3722 #[stable(feature = "iter_order", since = "1.5.0")]
3723 #[rustc_non_const_trait_method]
3724 fn cmp<I>(self, other: I) -> Ordering
3725 where
3726 I: IntoIterator<Item = Self::Item>,
3727 Self::Item: Ord,
3728 Self: Sized,
3729 {
3730 self.cmp_by(other, |x, y| x.cmp(&y))
3731 }
3732
3733 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3734 /// of another with respect to the specified comparison function.
3735 ///
3736 /// # Examples
3737 ///
3738 /// ```
3739 /// #![feature(iter_order_by)]
3740 ///
3741 /// use std::cmp::Ordering;
3742 ///
3743 /// let xs = [1, 2, 3, 4];
3744 /// let ys = [1, 4, 9, 16];
3745 ///
3746 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3747 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3748 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3749 /// ```
3750 #[unstable(feature = "iter_order_by", issue = "64295")]
3751 #[rustc_non_const_trait_method]
3752 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3753 where
3754 Self: Sized,
3755 I: IntoIterator,
3756 F: FnMut(Self::Item, I::Item) -> Ordering,
3757 {
3758 #[inline]
3759 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3760 where
3761 F: FnMut(X, Y) -> Ordering,
3762 {
3763 move |x, y| match cmp(x, y) {
3764 Ordering::Equal => ControlFlow::Continue(()),
3765 non_eq => ControlFlow::Break(non_eq),
3766 }
3767 }
3768
3769 match iter_compare(self, other.into_iter(), compare(cmp)) {
3770 ControlFlow::Continue(ord) => ord,
3771 ControlFlow::Break(ord) => ord,
3772 }
3773 }
3774
3775 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3776 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3777 /// evaluation, returning a result without comparing the remaining elements.
3778 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3779 ///
3780 /// # Examples
3781 ///
3782 /// ```
3783 /// use std::cmp::Ordering;
3784 ///
3785 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3786 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3787 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3788 /// ```
3789 ///
3790 /// For floating-point numbers, NaN does not have a total order and will result
3791 /// in `None` when compared:
3792 ///
3793 /// ```
3794 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3795 /// ```
3796 ///
3797 /// The results are determined by the order of evaluation.
3798 ///
3799 /// ```
3800 /// use std::cmp::Ordering;
3801 ///
3802 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3803 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3804 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3805 /// ```
3806 ///
3807 #[stable(feature = "iter_order", since = "1.5.0")]
3808 #[rustc_non_const_trait_method]
3809 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3810 where
3811 I: IntoIterator,
3812 Self::Item: PartialOrd<I::Item>,
3813 Self: Sized,
3814 {
3815 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3816 }
3817
3818 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3819 /// of another with respect to the specified comparison function.
3820 ///
3821 /// # Examples
3822 ///
3823 /// ```
3824 /// #![feature(iter_order_by)]
3825 ///
3826 /// use std::cmp::Ordering;
3827 ///
3828 /// let xs = [1.0, 2.0, 3.0, 4.0];
3829 /// let ys = [1.0, 4.0, 9.0, 16.0];
3830 ///
3831 /// assert_eq!(
3832 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3833 /// Some(Ordering::Less)
3834 /// );
3835 /// assert_eq!(
3836 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3837 /// Some(Ordering::Equal)
3838 /// );
3839 /// assert_eq!(
3840 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3841 /// Some(Ordering::Greater)
3842 /// );
3843 /// ```
3844 #[unstable(feature = "iter_order_by", issue = "64295")]
3845 #[rustc_non_const_trait_method]
3846 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3847 where
3848 Self: Sized,
3849 I: IntoIterator,
3850 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3851 {
3852 #[inline]
3853 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3854 where
3855 F: FnMut(X, Y) -> Option<Ordering>,
3856 {
3857 move |x, y| match partial_cmp(x, y) {
3858 Some(Ordering::Equal) => ControlFlow::Continue(()),
3859 non_eq => ControlFlow::Break(non_eq),
3860 }
3861 }
3862
3863 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3864 ControlFlow::Continue(ord) => Some(ord),
3865 ControlFlow::Break(ord) => ord,
3866 }
3867 }
3868
3869 /// Determines if the elements of this [`Iterator`] are equal to those of
3870 /// another.
3871 ///
3872 /// # Examples
3873 ///
3874 /// ```
3875 /// assert_eq!([1].iter().eq([1].iter()), true);
3876 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3877 /// ```
3878 #[stable(feature = "iter_order", since = "1.5.0")]
3879 #[rustc_non_const_trait_method]
3880 fn eq<I>(self, other: I) -> bool
3881 where
3882 I: IntoIterator,
3883 Self::Item: PartialEq<I::Item>,
3884 Self: Sized,
3885 {
3886 self.eq_by(other, |x, y| x == y)
3887 }
3888
3889 /// Determines if the elements of this [`Iterator`] are equal to those of
3890 /// another with respect to the specified equality function.
3891 ///
3892 /// # Examples
3893 ///
3894 /// ```
3895 /// #![feature(iter_order_by)]
3896 ///
3897 /// let xs = [1, 2, 3, 4];
3898 /// let ys = [1, 4, 9, 16];
3899 ///
3900 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3901 /// ```
3902 #[unstable(feature = "iter_order_by", issue = "64295")]
3903 #[rustc_non_const_trait_method]
3904 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3905 where
3906 Self: Sized,
3907 I: IntoIterator,
3908 F: FnMut(Self::Item, I::Item) -> bool,
3909 {
3910 #[inline]
3911 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3912 where
3913 F: FnMut(X, Y) -> bool,
3914 {
3915 move |x, y| {
3916 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3917 }
3918 }
3919
3920 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3921 }
3922
3923 /// Determines if the elements of this [`Iterator`] are not equal to those of
3924 /// another.
3925 ///
3926 /// # Examples
3927 ///
3928 /// ```
3929 /// assert_eq!([1].iter().ne([1].iter()), false);
3930 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3931 /// ```
3932 #[stable(feature = "iter_order", since = "1.5.0")]
3933 #[rustc_non_const_trait_method]
3934 fn ne<I>(self, other: I) -> bool
3935 where
3936 I: IntoIterator,
3937 Self::Item: PartialEq<I::Item>,
3938 Self: Sized,
3939 {
3940 !self.eq(other)
3941 }
3942
3943 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3944 /// less than those of another.
3945 ///
3946 /// # Examples
3947 ///
3948 /// ```
3949 /// assert_eq!([1].iter().lt([1].iter()), false);
3950 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3951 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3952 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3953 /// ```
3954 #[stable(feature = "iter_order", since = "1.5.0")]
3955 #[rustc_non_const_trait_method]
3956 fn lt<I>(self, other: I) -> bool
3957 where
3958 I: IntoIterator,
3959 Self::Item: PartialOrd<I::Item>,
3960 Self: Sized,
3961 {
3962 self.partial_cmp(other) == Some(Ordering::Less)
3963 }
3964
3965 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3966 /// less or equal to those of another.
3967 ///
3968 /// # Examples
3969 ///
3970 /// ```
3971 /// assert_eq!([1].iter().le([1].iter()), true);
3972 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3973 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3974 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3975 /// ```
3976 #[stable(feature = "iter_order", since = "1.5.0")]
3977 #[rustc_non_const_trait_method]
3978 fn le<I>(self, other: I) -> bool
3979 where
3980 I: IntoIterator,
3981 Self::Item: PartialOrd<I::Item>,
3982 Self: Sized,
3983 {
3984 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3985 }
3986
3987 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3988 /// greater than those of another.
3989 ///
3990 /// # Examples
3991 ///
3992 /// ```
3993 /// assert_eq!([1].iter().gt([1].iter()), false);
3994 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3995 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3996 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3997 /// ```
3998 #[stable(feature = "iter_order", since = "1.5.0")]
3999 #[rustc_non_const_trait_method]
4000 fn gt<I>(self, other: I) -> bool
4001 where
4002 I: IntoIterator,
4003 Self::Item: PartialOrd<I::Item>,
4004 Self: Sized,
4005 {
4006 self.partial_cmp(other) == Some(Ordering::Greater)
4007 }
4008
4009 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4010 /// greater than or equal to those of another.
4011 ///
4012 /// # Examples
4013 ///
4014 /// ```
4015 /// assert_eq!([1].iter().ge([1].iter()), true);
4016 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
4017 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
4018 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
4019 /// ```
4020 #[stable(feature = "iter_order", since = "1.5.0")]
4021 #[rustc_non_const_trait_method]
4022 fn ge<I>(self, other: I) -> bool
4023 where
4024 I: IntoIterator,
4025 Self::Item: PartialOrd<I::Item>,
4026 Self: Sized,
4027 {
4028 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
4029 }
4030
4031 /// Checks if the elements of this iterator are sorted.
4032 ///
4033 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4034 /// iterator yields exactly zero or one element, `true` is returned.
4035 ///
4036 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4037 /// implies that this function returns `false` if any two consecutive items are not
4038 /// comparable.
4039 ///
4040 /// # Examples
4041 ///
4042 /// ```
4043 /// assert!([1, 2, 2, 9].iter().is_sorted());
4044 /// assert!(![1, 3, 2, 4].iter().is_sorted());
4045 /// assert!([0].iter().is_sorted());
4046 /// assert!(std::iter::empty::<i32>().is_sorted());
4047 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
4048 /// ```
4049 #[inline]
4050 #[stable(feature = "is_sorted", since = "1.82.0")]
4051 #[rustc_non_const_trait_method]
4052 fn is_sorted(self) -> bool
4053 where
4054 Self: Sized,
4055 Self::Item: PartialOrd,
4056 {
4057 self.is_sorted_by(|a, b| a <= b)
4058 }
4059
4060 /// Checks if the elements of this iterator are sorted using the given comparator function.
4061 ///
4062 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4063 /// function to determine whether two elements are to be considered in sorted order.
4064 ///
4065 /// # Examples
4066 ///
4067 /// ```
4068 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
4069 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
4070 ///
4071 /// assert!([0].iter().is_sorted_by(|a, b| true));
4072 /// assert!([0].iter().is_sorted_by(|a, b| false));
4073 ///
4074 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
4075 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
4076 /// ```
4077 #[stable(feature = "is_sorted", since = "1.82.0")]
4078 #[rustc_non_const_trait_method]
4079 fn is_sorted_by<F>(mut self, compare: F) -> bool
4080 where
4081 Self: Sized,
4082 F: FnMut(&Self::Item, &Self::Item) -> bool,
4083 {
4084 #[inline]
4085 fn check<'a, T>(
4086 last: &'a mut T,
4087 mut compare: impl FnMut(&T, &T) -> bool + 'a,
4088 ) -> impl FnMut(T) -> bool + 'a {
4089 move |curr| {
4090 if !compare(&last, &curr) {
4091 return false;
4092 }
4093 *last = curr;
4094 true
4095 }
4096 }
4097
4098 let mut last = match self.next() {
4099 Some(e) => e,
4100 None => return true,
4101 };
4102
4103 self.all(check(&mut last, compare))
4104 }
4105
4106 /// Checks if the elements of this iterator are sorted using the given key extraction
4107 /// function.
4108 ///
4109 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4110 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4111 /// its documentation for more information.
4112 ///
4113 /// [`is_sorted`]: Iterator::is_sorted
4114 ///
4115 /// # Examples
4116 ///
4117 /// ```
4118 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4119 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4120 /// ```
4121 #[inline]
4122 #[stable(feature = "is_sorted", since = "1.82.0")]
4123 #[rustc_non_const_trait_method]
4124 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4125 where
4126 Self: Sized,
4127 F: FnMut(Self::Item) -> K,
4128 K: PartialOrd,
4129 {
4130 self.map(f).is_sorted()
4131 }
4132
4133 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4134 // The unusual name is to avoid name collisions in method resolution
4135 // see #76479.
4136 #[inline]
4137 #[doc(hidden)]
4138 #[unstable(feature = "trusted_random_access", issue = "none")]
4139 #[rustc_non_const_trait_method]
4140 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4141 where
4142 Self: TrustedRandomAccessNoCoerce,
4143 {
4144 unreachable!("Always specialized");
4145 }
4146}
4147
4148trait SpecIterEq<B: Iterator>: Iterator {
4149 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4150 where
4151 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4152}
4153
4154impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4155 #[inline]
4156 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4157 where
4158 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4159 {
4160 iter_eq(self, b, f)
4161 }
4162}
4163
4164impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4165 #[inline]
4166 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4167 where
4168 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4169 {
4170 // we *can't* short-circuit if:
4171 match (self.size_hint(), b.size_hint()) {
4172 // ... both iterators have the same length
4173 ((_, Some(a)), (_, Some(b))) if a == b => {}
4174 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4175 ((_, None), (_, None)) => {}
4176 // otherwise, we can ascertain that they are unequal without actually comparing items
4177 _ => return false,
4178 }
4179
4180 iter_eq(self, b, f)
4181 }
4182}
4183
4184/// Compares two iterators element-wise using the given function.
4185///
4186/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4187/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4188/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4189/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4190/// the iterators.
4191///
4192/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4193/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4194#[inline]
4195fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4196where
4197 A: Iterator,
4198 B: Iterator,
4199 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4200{
4201 #[inline]
4202 fn compare<'a, B, X, T>(
4203 b: &'a mut B,
4204 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4205 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4206 where
4207 B: Iterator,
4208 {
4209 move |x| match b.next() {
4210 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4211 Some(y) => f(x, y).map_break(ControlFlow::Break),
4212 }
4213 }
4214
4215 match a.try_for_each(compare(&mut b, f)) {
4216 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4217 None => Ordering::Equal,
4218 Some(_) => Ordering::Less,
4219 }),
4220 ControlFlow::Break(x) => x,
4221 }
4222}
4223
4224#[inline]
4225fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4226where
4227 A: Iterator,
4228 B: Iterator,
4229 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4230{
4231 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4232}
4233
4234/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4235///
4236/// This implementation passes all method calls on to the original iterator.
4237#[stable(feature = "rust1", since = "1.0.0")]
4238impl<I: Iterator + ?Sized> Iterator for &mut I {
4239 type Item = I::Item;
4240 #[inline]
4241 fn next(&mut self) -> Option<I::Item> {
4242 (**self).next()
4243 }
4244 fn size_hint(&self) -> (usize, Option<usize>) {
4245 (**self).size_hint()
4246 }
4247 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4248 (**self).advance_by(n)
4249 }
4250 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4251 (**self).nth(n)
4252 }
4253 fn fold<B, F>(self, init: B, f: F) -> B
4254 where
4255 F: FnMut(B, Self::Item) -> B,
4256 {
4257 self.spec_fold(init, f)
4258 }
4259 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4260 where
4261 F: FnMut(B, Self::Item) -> R,
4262 R: Try<Output = B>,
4263 {
4264 self.spec_try_fold(init, f)
4265 }
4266}
4267
4268/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4269trait IteratorRefSpec: Iterator {
4270 fn spec_fold<B, F>(self, init: B, f: F) -> B
4271 where
4272 F: FnMut(B, Self::Item) -> B;
4273
4274 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4275 where
4276 F: FnMut(B, Self::Item) -> R,
4277 R: Try<Output = B>;
4278}
4279
4280impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4281 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4282 where
4283 F: FnMut(B, Self::Item) -> B,
4284 {
4285 let mut accum = init;
4286 while let Some(x) = self.next() {
4287 accum = f(accum, x);
4288 }
4289 accum
4290 }
4291
4292 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4293 where
4294 F: FnMut(B, Self::Item) -> R,
4295 R: Try<Output = B>,
4296 {
4297 let mut accum = init;
4298 while let Some(x) = self.next() {
4299 accum = f(accum, x)?;
4300 }
4301 try { accum }
4302 }
4303}
4304
4305impl<I: Iterator> IteratorRefSpec for &mut I {
4306 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4307
4308 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4309 where
4310 F: FnMut(B, Self::Item) -> R,
4311 R: Try<Output = B>,
4312 {
4313 (**self).try_fold(init, f)
4314 }
4315}